Do While in C
1.What is Do while in C ?
Ans: The do…while in C is a loop statement used to repeat some part of the code till the given condition is fulfilled. It is a form of an exit-controlled or post-tested loop where the test condition is checked after executing the body of the loop. Due to this, the statements in the do…while loop will always be executed at least once no matter what the condition is.
Simple Explanation :
In image we can see that two boys are fighting because they are not aware about the situation after the fight. The first fight and after fighting they see the situation occurred due to fight.
The do while loop also do same work. It first perform function and after performing it will check the condition. The loop will stop if till the condition will not become false.
Working of Do while loop :
Output :
#include <stdio.h> int main()
{ int num, sum = 0; // Declare variables to store the entered number and the sum // Prompt the user to input integers until they enter 0 do
{ printf("Input an integer (enter 0 to stop): "); scanf("%d", &num); // Read the entered number if (num > 0)
{ sum += num; // Add the positive number to the sum
}
else if (num < 0)
{ printf("Negative integers are not considered. Ignored.\n");
} }
while (num != 0); // Continue the loop until the user enters 0 // Print the sum of positive integers printf("Sum of positive integers: %d\n", sum); }
Output :
0 Comments