Understanding the Do-While Loop in C Programming
Unlike for and while loops, which test the loop condition at the top of the loop. The do-while loop in C programming checks its condition at the bottom of the loop. The do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.
- The first body of the loop is executed.
- The condition check to true, the body of the loop inside the do statement is executed again.
- The condition is check again.
- This process continues until the condition is false.
- When the condition to false, the loop stops.
Syntax:
do
{
// body of loop;
// Increment (or) Decrement;
} while(Condition)
The program is written in C and it demonstrates the use of the do-while loop
- The program starts with the inclusion of the header file "stdio.h" which contains the function printf() used in the program.
- The program declares an integer variable "i" and initializes it with 0. Then it prompts the user to enter a limit using the scanf() function and stores the value in the variable "n".
- The program then enters a do-while loop, which is a variation of the while loop. The structure of the do-while loop is such that the code block inside the loop is executed at least once before the condition is checked.
- Inside the do-while loop, the program uses the printf() function to print the value of the variable "i" and then it increments the value of "i" by 2 using the increment operator (i+=2) which is a shorthand for i=i+2.
- The do-while loop continues to execute until the value of "i" becomes greater than "n". Once the condition becomes false, the program exits the do-while loop and continues to execute the next statement after the loop.
- Finally, the program returns 0 to indicate successful execution.
In this program, the do-while loop will print all the even numbers from 0 to n (inclusive) that the user entered. So, the program will print 0, 2, 4 ... n numbers.
Source Code
//Do While
/*
do
{
-----
-----
}while(condition);
*/
#include<stdio.h>
int main()
{
int i=0,n;
printf("\nEnter The Limit : ");
scanf("%d",&n);
do
{
printf("\n%d",i);
i+=2; //i=i+2
}while(i<=n);
return 0;
}
To download raw file
Click Here
Output
Enter The Limit : 30
0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30