C documentation V1 Help

While and Do-While Loops

In addition to the for loop, C provides the while and do-while loops for iterating through code blocks based on certain conditions. Let's explore the syntax and usage of both the while and do-while loops.

1. While Loop

#include <stdio.h> int main() { int count = 1; // Example of a while loop while (count <= 5) { printf("Iteration %d\n", count); count++; } return 0; }

Explanation of the Program:

  1. The while loop continues to execute the code block as long as the specified condition (count <= 5) is true.

  2. In each iteration, the body of the loop is executed, and the loop variable (count) is updated (count++).

  3. The loop prints "Iteration 1" to "Iteration 5" in this example.

2. Do-While Loop

#include <stdio.h> int main() { int x = 5; // Example of a do-while loop do { printf("Value of x: %d\n", x); x--; } while (x > 0); return 0; }

Explanation of the Program:

  1. The do-while loop is similar to the while loop, but it ensures that the code block is executed at least once before checking the condition.

  2. In this example, the loop prints the value of x and decrements it until x becomes 0.

  3. Even if the initial condition is false, the code block executes at least once.

Practical Tips

  • Use the while loop when the number of iterations is not known in advance.

  • The do-while loop is suitable when you want to guarantee that the code block runs at least once.

Understanding and utilizing while and do-while loops provide flexibility in handling different looping scenarios in C programming. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask. Happy coding!

Last modified: 25 February 2024