Control Statements (Looping) While-Do While and For
Control Statements (Looping) While-Do While and For
Output:
The sum of 10 natural numbers is: 55
Example 2: program which uses do while loop for printing numbers 1 to
10.
#include <stdio.h>
int main()
{ int i=1;
do
{
printf(“Number is: %d\n”,i);
i=i+1;
}
while( i<=10);
return 0; }
FOR Loop:
This is another entry control loop.
This integrates 3 basic ingredients of a loop (initialization,
condition and incrementing).
For loop is typically used to repeat statements for a fixed number
of times.
The basic form of for statement:
Syntax:
for(initialization;condition;updation)
{
statement;
}
Initialization Executed only for once just before loop
starts. Normally counter (variable used in
loop) is initialized here.
condition Is any valid C condition. As long as this
is true statement is repeatedly executed.
updation Executed after the statement is executed.
Typically contains incrementing counter or
decrementing counter as the case may be
statement (Body of the loop) This is repeatedly
executed as long as condition is true. It may
be a compound statement also.
Example 1: program which uses for loop for printing numbers 1 to 10.
#include <stdio.h> output :
int main() Number: 1
{ Number: 2
int i; Number: 3
for( i=1; i<= 10; i++) Number: 4
{ Number: 5
printf(“Number: %d\n”,i); Number: 6
} Number: 7
return 0; Number: 8
} Number: 8
Number: 10
Program for finding sum of series: 1+2+3+4+……………..+n
#include <stdio.h>
main()
{
int i,n,sum=0;
printf(“Give the Number of n:”);
scanf(“%d”,&n);
for( i=1; i<= n; i++)
{
sum = sum+i;
}
printf(“The sum of the series is: %d”,sum);
return 0;
}
If you run this program and give 5 as value of n then it will print:
The sum of the series is:15
END