All submissions

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) {
    // Implement using function pointer array
    void(*ptr1)()=state_init;
    void(*ptr2)()=state_load;
    void(*ptr3)()=state_execute;
    void(*ptr4)()=state_exit;
    
    if(start==0)
    {
        ptr1();
        ptr2();
        ptr3();
    }

    if(start==1)
    {
        ptr2();
        ptr3();
        ptr4();
    }

    if(start==2)
    {
        ptr3();
        ptr4();
        ptr1();
    }

    if(start==3)
    {
        ptr4();
        ptr1();
        ptr2();
    }
}

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

Solving Approach

 

 

 

Loading...

Input

0

Expected Output

Init Load Execute