Looping Statements in C for SEE and NEB
Introduction:
Looping (Repetitive Structure):
Loops follow the iteration concept. Loops allow a set of instructions to be performed until a certain condition becomes false. This condition may be predefined or opened. Different types of loops are as here under:
- The FOR loop.
- The WHILE loop
- The DO……….WHILE loop
a) For Loop:
The for statement makes programming more convenient to count iterations of a loop and works well where the number of iterations of the loop is known before the loop is entered.
- Loop’s initial value i.e. to set loops starting value.
- Test condition i.e. to determine the number of repetitions
- increment or decrement value
Syntax:
For(initialization; test-condition;increment/decrement)
{
statement;
-----------;
}
Example
1: To display the natural numbers from 1 to 10 vertical.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
printf("\n%d",i);
}
getch();
}
Output:
Example
2: To display the natural numbers from 1 to 10 horizontal.
#include<stdio.h>
#include<conio.h>
main()
{
int
i;
for(i=1;i<=10;i++)
{
printf("%d\t",i);
}
getch();
}
Output:
Syntax:
while(expression)
{
statement;
increment/decrement;
}
Example: WAP to display the
natural numbers 1 to 10.
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int i=1;
while(i<=10)
{
printf("%d\t",i);
i++;
}
getch();
}
c) Do…….While
Loop:
The do……while
loop is sometimes referred to as do……loop in ‘C’. Unlike for and while loops,
this loops checks its condition at the end of the loop, that is, after the
loops has been executed. This means that
do ……while loop will execute at least once, even if the condition is false
initially.
Syntax:
do
{
statement;
increment/decrement;
} while(condition);
Example:
WAP to display the natural number 1 to 10.
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a=1;
do
{
printf("\n%d ",a);
a++;
}
while(a<=10);
getch();
}
You can also Read:
No comments:
Post a Comment