LOOPING STATEMENTS / ITERATIVE STATEMENTS:
In Loop, sequence of statements are executed until a specified condition is
true.
This sequence of statements to be executed is kept inside the curly braces { }
known as the Loop
body.
After every execution of loop body, condition is verified, and if it is found to
be true the loop body is
executed again. When the condition check returns false, the loop body is not
executed.
There are 3 type of Loops in C language
● For loop
● while loop
● do-while loop
while Loop:
Description:
Step 1: The while condition is checked first.
Step 2: If the condition is true, the statements inside the loop will be executed,
then the variable
value is incremented or decremented at the end of the looping statement.
Step 3: If the condition is false, the loop body will be skipped and the
statements after the while loop will be executed.
Sum of n natural numbers using while loop
#include<stdio.h>
int main()
{
int n,i=1,sum = 0;
printf("Enter a number\n");
scanf("%d",&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf("The sum of nos: %d\n",sum);
return(0);
}
do while loop:
It is an exit controlled looping statement.
The do-while loop checks its condition at the bottom of the loop whereas for
and while loops,
the loop condition is checked at the top of the loop.
do-while loop is guaranteed to execute the statement at least one time.
Program to print multiples of 5:
#include<stdio.h>
int main()
{
int a=5,i=1;
do
{
printf("%d\n",a*i);
i++;
}
while(i <= 10);
}
for loop:
for loop is used to execute a set of statements repeatedly until a particular
condition is satisfied.
Flow of Execution:
[Link] initialization step is executed first, and only once. This step allows
to declare and initialize any loop control variables.
[Link], the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop will not be executed and flow of
control jumps to the next statement just after the for loop.
[Link] the body of the for loop executes, the flow of control jumps back
up to the increment statement. This statement allows to update any loop control
variables.
[Link] condition is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then increment step, and then again
condition). When the condition becomes false, the for loop terminates.
Printing n natural numbers:
#include <stdio.h>
int main(){
int n,i;
printf("enter the maximum no to be printed:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("%d\n",i); //
}
return(0);}