Image

C Language - Control Statements - looping

Looping

It is used to execute group of statement repeatedly till the condition is satisfy.

C support three types of looping statement.
1.while loop
2.do while loop
3.for loop.
Basically in looping statement three things are included and that are most important .
1 initialization
2 condition
3 updation .
By using initialization we initialize the variable and after that it check the condition and in updation it increment or decrement the variable.

1.While loop
When we don’t know the ending point of any execution at that time we used while loop .it is used execute the group of statement repeatedly till condition is satisfy.
Syntax: Initialization ;
	        While(condition)
	        {
		Block of statement//
                }
Flowchart

Ex:WAP to print hello world using while loop
#include<stdio.h>
#include<conio.h>
void main()
{
   int i=1;
   clrscr();
   while(i<=5)
   {
    printf("\n Hello world");
    i++;
   }
   getch();
}
o/p
   	 Hello world
         Hello world
         Hello world
         Hello world
         Hello world	

Do while loop

The main difference here is the condition is tested after the body of the loop and the statement in the body will be executed at least once whether the condition is true or false. This is not the case with the other two loops where if the condition is false at the beginning, then the body of the loop is not executed at all. Notice the semicolon at the end of the while line of code.

Syntax: initialization;
	do
	{
	 Block of statement//
	}while(condition);
Flowchart

EX: Find the factorial of a number
#include<stdio.h>
#include<conio.h>
main()
{
int n, num, factorial = 1;
printf ("Enter the number:");
scanf ("%d", &n);
num = n;
	if (n < 0)
		printf ("\n factorial of negative number not possible:");
	else
	if (n = = 0)
		printf ("Factorial of 0 is 1 \n");
	else
	do
	{
		factorial * = n;
		n - -;
	}
	while (n > 1);
printf ("factorial of % d = % d", no, fact);
}
o/p
if the value entered is 5, the program outputs 120 (i.e., 5 * 4 * 3 * 2 * 1).

3.For Loop

A for loop allows execution of a statement (or a block of statements) repeatedly a number of times. When the number of times a statement is to be executed is known in advance, for loop is particularly useful. The syntax of for loop in C language is as follows

Syntax:
             for(<initialization>; <condition>; <modification>)
		{
		statement-1;
		}
Flowchart

EX: program to print number from 1 to 5
#include<stdio.h>
#include<conio.h>
main( )
{
int i;
clrscr();
for (i = 1; i <= 5; i ++)
	printf ("%d \n", i);
getch();
}
o/p
1
2
3
4
5