All submissions

State Machine Using Function Pointers

h zeCode

#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) 
{
    void (*ptr[4])()={state_init,state_load,state_execute,state_exit};
    int count=0; 
    while(count<3)
    {
        ptr[start]();
        printf("\n");
        count++;
        start=(start+1)%4;
    }
}

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

Solving Approach

1:  We need to initially declare array of function pointers and store all the address into it for the four function in the same order as they are defined.

2: Take a variable: count and initialize with zero. As we need to run the loop 3 times only.

3: invoke function call using function pointer to respective index which is passed from user.

4: Key point is we need to increment the start such that it follows the approach of traversing in circular queue.

start=(start+1)%size; //In this case size:4 as there are only functions being pointed.

 

 

 

Loading...

Input

0

Expected Output

Init Load Execute