Loop Statements

Girdhar Gopal Singh  Print 
09 Aug 2018
08 Sep 2018
Intermediate
1.26K

Loops are used to repeat a block of statements for a certain times. C offers four types of loops– while, do-while, for.

While

This loop executes a statement or a block of statements until the specified boolean expression evaluates to false. Typically, while loop is useful when you are not aware of exact number of iterations.

#include<stdio.h>
#include<conio.h>
void main()
{
 clrscr();
 int number = 5;
 while (number != 0) //specified boolean expression
 {
 printf("Current value of n is %d", number);
 number--; //update statement 
 }
 getch();
}
/* Output:
 Current value of n is 5
 Current value of n is 4
 Current value of n is 3
 Current value of n is 2
 Current value of n is 1
*/

Do-While Loop

This loop executes a statement or a block of statements until the specified boolean expression evaluates to false. Typically, while loop is useful when you are not aware of exact number of iterations.

#include<stdio.h>
#include<conio.h>
void main()
{
 clrscr();
 char choice = 'Y';
 do
 {
 int number = 5;

 printf("\nPrint Number : %d", number);

 printf("\nDo you want to continue (y/n) :");
 scanf("%c",&choice);

 } while (choice == 'y'); //specified boolean expression

 getch(); 
}
/*
 Output:
 Print Number : 5
 Do you want to continue (Y/N) :y

 Print Number : 5
 Do you want to continue (Y/N) :n
*/

For Loop

This loop has three sections - index declaration, condition (boolean expression) and updation section. In each for loop iteration, the index is updated (incremented/decremented) by updating section and checked with the condition. If the condition is matched, it continues execution until the specified boolean expression evaluates to false. Typically, for loop is useful when you are aware of exact number of iterations. Normally, it is used for iterating over arrays and for sequential processing.

#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
 int a,f,i;
 printf("Enter a number: ");
 scanf("%d",&a);
 f=1;
 for(i=1;i<=a;i++)
 f = f * i;
 printf("Factorial: %d",f);
getch();
}
/*
Output:
Enter a number:5
Factorial:120
Enter a number:4
Factorial:24
*/
Hands-on Learning
Free Interview Books
 
+