English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to create while and do ... while loops in C programming with the help of examples.
In programming, loops are used to repeat code blocks until a specified condition is met.
C programming has three types of loops.
While loop
do... while loop
In the previous tutorial, we learned about the for loop. In this tutorial, we will learn about the while and do..while loops.
The syntax of the while loop is:
while (testExpression) { // Statements within the loop body }
The while loop calculates the test expression (testExpression) within the parentheses.
If the test expression (testExpression) is true, execute the statements within the loop body. Then, evaluate the test expression (testExpression) again.
This process continues until the test expression (testExpression) is evaluated as false.
If the test expression is false (false), the loop terminates (ends).
To learn more about the test expression (when the test expression is evaluated as true and false), please seerelationoperatorandLogical operators.
//Print from1to5the numbers #include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("%d\n", i); ++i; } return 0; }
Output Result
1 2 3 4 5
Here, we have initialized i to1.
when i is1when the test expression i <= 5 is true. Therefore, the loop body is executed. Print on the screen1, and increase the value of i to2.
Now i is2, the test expression i <= 5 Again, the test expression is true. The loop body will execute again. Print on the screen2, and increase the value of i to3.
This process continues until i is6at this time, the test expression i <= 5 is false, the loop terminates.
The do..while loop is similar to the while loop, but there is an important difference.The body of the do...while loop is executed at least once. The test expression is evaluated only after one execution.
The syntax of the do...while loop is:
do { //Statements within the loop body } while (testExpression);
The body of the do...while loop is executed once. Only after this execution is the test expression evaluated.
If the test expression (testExpression) is true, the loop body is executed again and the test expression (testExpression) is evaluated again.
This process continues until the test expression becomes false.
The loop ends if the test expression is false.
//The program adds numbers until the user enters zero #include <stdio.h> int main() { double number, sum = 0; //The body of the loop must be executed at least once do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0); printf("Sum = %.2lf",sum); return 0; }
Output Result
Enter a number: 1.5 Enter a number: 2.4 Enter a number: -3.4 Enter a number: 4.2 Enter a number: 0 Sum = 4.70