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"); }

void start_0()
{
    state_init();
    state_load();
    state_execute();
}

void start_1()
{
    state_load();
    state_execute();
    state_exit();
}

void start_2()
{
    state_execute();
    state_exit();
    state_init();
}

void start_3()
{
    state_exit();
    state_init();
    state_load();
}

typedef void (*func_ptr)(void);

func_ptr boot_func[] =
{
    start_0,
    start_1,
    start_2,
    start_3
};

// Your logic here
void run_state_sequence(int start) 
{
    boot_func[start]();
}

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