Looping
Looping Statements: A computer program is a set of statements, which is normally executed sequentially. But in most of the cases, it is necessary to repeat certain steps to meet a specific condition. This repetitive operation is done through a loop control structure. A loop is basically the execution of the sequence of statements repeatedly until a particular condition is true or false. In ‘C’ language following looping statements are used:
while Statements: The while loop repeats a statement or a set of statements until a certain condition is true. Syntax
while (condition)
{
statements
}
Here, the condition may be any expression having a non-zero value. The loop continues until the condition is true. When the condition fails, the program body attached with loop (statements), will not be executed.
Example: To print the first 20 natural numbers.
#include<stdio.h>
#include<conio.h>
void main ()
{
int a = 1;
while (a < = 20)
{
printf (“%d” , a);
a++;
}
getch ();
}
do-while statement: Working of this statement is similar to the working of while statement but in this, at least one time the attached loop (statements) is executed, no matter whether the condition is true or false.
Synax:
do
{
statements
}
while (condition);
Example: To print first 10 odd numbers.
#include<stdio.h>
#include<conio.h>
void main ()
{
int a = 1;
do
{
printf (“% d” , a);
a+ = 2;
{while (a <=19)};
}
for loop statement:
The for loop is an ideal looping statement when we know how many times the loop will be executed.
Syntax:
for (initialization; condition; counter)
{
statements
}
Here,
- Initialization is generally an assignment which is used to set the loop control variable, e.g., a = 0.
- Condition always tells the limit of the loop or determines when to exit the loop. e.g., a < 10
- Counter defines how the loop control variable will change each time the loop is repeated. This may be incremented or decremented. e.g., a++, a- -.
Example: To print your name 10 times.
#include<stdio.h>
#include<conio.h>
void main ()
{
int i;
char name [20];
clrscr ();
printf (“Enter your name”);
gets(name);
for (i = 1; i <= 10; i++)
puts (name);
}
getch ();
}