C Programming While and Do
C Programming While and Do
while Loop
Syntax of while loop
while (test expression) {
statement/s to be executed.
}
The while loop checks whether the test expression is true or not. If it is true, code/s inside the body of while
loop is executed,that is, code/s inside the braces { } are executed. Then again the test expression is checked
whether test expression is true or not. This process continues until the test expression becomes false.
Output
Enter a number.
5
Factorial=120
do...while loop
In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in while
loops, test expression is checked at first but, in do...while loop code is executed at first then the condition is
checked. So, the code are executed at least once in do...while loops.
At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s inside
body of do are executed again and the process continues until test expression becomes false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
In this C program, user is asked a number and it is added with sum. Then, only the test condition in the
do...while loop is checked. If the test condition is true,i.e, num is not equal to 0, the body of do...while loop is
again executed until num equals to zero.