State Machine Using Function Pointers

Code

#include <stdio.h>

void state_init()    { printf("Init"); }
void state_load()    { printf("Load"); }
void state_execute() { printf("Execute"); }
void state_exit()    { printf("Exit"); }

// // Your logic here
// void run_state_sequence(int start) {
//     // Implement using function pointer array
//     void (*const ops[])(void) = {state_init,state_load,state_execute,state_exit};
//     // for (int i = start; i < start + 3;i++){
//     //     int j = i;
//     //     if (i > 3) {j = i - 3;}
//     //     ops[j]();
//     //     printf("\n");
//     // }



void run_state_sequence(int start) {
    // Array of function pointers: each has signature void(void)
    void (*const ops[])(void) = { state_init, state_load, state_execute, state_exit };
    const int N = (int)(sizeof ops / sizeof ops[0]); // N == 4

    // Execute exactly three states, wrapping with modulo (no if/switch)
    for (int k = 0; k < 3; ++k) {
        int idx = (start + k) % N;  // 0..3 with wrap-around
        ops[idx]();                 // <-- call the function at index idx
        printf("\n");
        }
}



int main() {
    int start;
    scanf("%d", &start);
    run_state_sequence(start);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

0

Expected Output

Init Load Execute