C programming while and do...while Loop
C programming loops
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied, i.e., loops are used in performing repetitive work in programming.
Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s only one time and repeat the execution 10 times using loop.
There are 3 types of loops in C programming:
- for loop
- while loop
- 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.Example of while loop
Write a C program to find the factorial of a number, where the number is entered by user. (Hints: factorial of
n = 1*2*3*...*n
/*C program to demonstrate the working of while loop*/
#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0){ /* while loop continues util test condition number>0 is true */
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}
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.
Syntax of do...while loops
do { some code/s; } while (test expression);
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.
Example of do...while loop
Write a C program to add all the numbers entered by a user until user enters 0.
/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}
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.
No comments:
Post a Comment