State Machine Using Function Pointers

Code

#include <stdio.h>

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

// Your logic here
void run_state_sequence(int start) {
    if(start == 0){
        void (*ptr)();
        ptr= state_init;
        ptr();
        ptr= state_load;
        ptr();
        ptr= state_execute;
        ptr();

    }if(start == 1){
        void (*ptr)();
        ptr= state_load;
        ptr();
        ptr= state_execute;
        ptr();
        ptr= state_exit;
        ptr();

    }if(start == 2){
        void (*ptr)();
        ptr= state_execute;
        ptr();
        ptr= state_exit;
        ptr();
        ptr= state_init;
        ptr();

    }if(start == 3){
        void (*ptr)();
        ptr= state_exit;
        ptr();
        ptr= state_init;
        ptr();
        ptr= state_load;
        ptr();

    }
    // Implement using function pointer array
}

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