do while loop in C | syntax

 

do while loop in C

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.

do while loop in C


Here's the syntax of a do-while loop:

c
do { // Code to be executed } while (condition);


Here's how a do-while loop works:

1. The code block inside the do is executed.
2. After executing the code block, the condition inside the while is evaluated.
3. If the condition is true, the loop will continue, and the code block will be executed again.
4. If the condition is false, the loop terminates, and program control continues after the do-while loop.
  1. Example .

    c
    #include <stdio.h> int main() { char input; printf("Enter characters (q to quit):\n"); do { scanf(" %c", &input); // Read a character from the user // Check if the entered character is 'q' (quit) if (input == 'q') { printf("Quitting the loop.\n"); } else { printf("You entered: %c\n", input); } } while (input != 'q'); // Continue looping until 'q' is entered return 0; }

    Flowchart of do while loop
    do while loop in C

    Here's an example of a simple do-while loop that counts from 1 to 5:

    c
    #include <stdio.h> int main() { int count = 1; do { printf("%d\n", count); count++; } while (count <= 5); return 0; }

Post a Comment

0 Comments