loop control statements

Loop control structure

It involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied.

Types of looping

  • While statement
  • For statement
  • Do- while statement

While loop:

While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

Syntax :

While (condition)
Statement block

Flow of while loop
Test the condition
If condition is true then execute the statement block and repeat steps until the condition become false.

Demonstration of while loop
#include<stdio.h>
#include<conio.h>
Void main(){
int i=0 n;
printf(“enter a number”);
while(i =>n )
{
printf(“%d \t”,digit);
i++;
}
}

For loop

For loop is count controlled loop in the sense that the program knows in advance how many times the loop is to be executed .

General form of for loop

For(initialization; expression; increment or decrement )
Statement block
 Demonstration of for loop
#include<stdio.h>
#include<conio.h>
void main(){
int n;
printf(“enter any number ”);
scanf(“%d”,&n);
for (i=0; i<=n;i++){
printf(“%d\n”,i);
}
}

Do while loop

It is almost same as while loop and used in the problem where it is not known in advance that how many times a statement block will be executed.

do
statement block
while(condition);

Demonstration of do while loop

Program to calculate the sum of first n numbers using do while loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int sum, n, i=0;
sum=0;
printf(“\n enter the value of n”);
scanf(“%d”,&n);
do{
sum+=I;
i++;
}
while(i<=n);
printf(“sum of  first %d nimbers=%d”,n,sum);
}

Output:
Enter the value of n 10
Sum of first 10 numbers = 55

Jumping statement

Jumping statements are used to transfer the control from one part of the program to another part.

  1. the break statement
  2. The continue statement
  3. The goto  statement

Break statement

  1. The break statement is always used inside the body of the switch statement .
  2. It can also be used in any of the statement .
Demonstration of break statement
#include<stdio.h>
#include<conio.h>
void main(){
int i;
for(i=1; i<=10;i++)
{
printf(“\n%d”,i);
if(i==3){
printf(“\n ok bye”);
break;}
printf(“\n next”);
}
getch();
}

Continue statement
The continue statement is used inside the body of the loop statement .
The break statement terminates the loop , while the continue statement does’t  terminate the loop but transfers the control back to the first statement.

The goto statement :
It is unconditional transfer of control which means that the sequence of execution will be broken without performing any test and the control will be transferred to some statement other than the immediate next one.

Syntax:
goto <statement label>
#include<stdio.h>
void main(){
float x;
scanf(“%f”,&x);
while(x<=50){
if(x<0)
goto error;
scanf(“%f”,&x);
}
Error: printf(“negative value error”);
}