Hello
Is this a homework or academic assignment?
Is it a new topic or related to your last topic? They look similar.
A clear statement of the problem helps.
Add some comments to your code.
Consider drawing a “state diagram”:
State Diagram
I use state diagrams and flowcharts for my more complex code.
Hint to get you started:
Try putting flag = 0;
at the end of if statements in the main loop; try one at a time and observe.
That is it for now…