C do while loop
Created By: chatGPT
C provides a control flow statement called the do while
loop, which enables you to execute a block of code at least once. The do while
loop checks the condition after executing the loop's body, ensuring that the code runs before the condition is evaluated. This is useful in scenarios where you want to ensure the execution irrespective of the condition.
Here’s the syntax for a do while
loop:
c do { // Code to be executed } while (condition);
// Example of a do while loop in C
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Count is: %d\n", count);
count++;
} while (count <= 5);
return 0;
}
In this example, the loop will print the value of count from 1
to 5
.
- The initial value of
count
is set to1
. - The
do
block is executed, printing the current value ofcount
. - After printing,
count
is incremented by1
. - The condition in the
while
statement (count <= 5
) is checked after each execution of the loop.
As a result, you'll see:
plaintext Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
do
block will still be executed once, but it will not continue to loop afterward. This is the key difference between do while
and other loops like while
or for
, where the condition is checked before executing the block of code.