Professional Documents
Culture Documents
Chap 5 Looping
Chap 5 Looping
• - for loop
• - while loop
• - do while loop
for loops
The basic format of the for statement is,
for( start_condition; continue_ condition; re-evaluation )
{
program statement;
}
Sample program using a for statement
#include <stdio.h>
main()
{
int count;
for(count= 1;count<= 10;count=count+1)
printf("%d\t",count);
}
Sample Program Output 1 2 3 4 5 6 7 8 9 10
An example of using a for loop to print out characters
#include<stdio.h>
main()
{
char letter;
for( letter = 'A'; letter <= 'E'; letter = letter + 1 )
{
printf("%c ", letter);
}
}
#include<stdio.h>
main()
{
int i,n,sum=0;
printf("ENTER THE LIMIT\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf("\n THE SUM OF FIRST %d NUMBERS = %d", n, sum);
}
MULTIPLICATION TABLE
#include<stdio.h>
main()
{
int i,table,counter=1;
}
Program that display multiplication table
from 1 to 10
#include<stdio.h>
main()
{
int i,j;
for(i=1;i<=10;i++)
{for(j=1;j<=10;j++)
{
printf("%d x %d = %d\n",i,j,i*j);
}
printf("\n\n");
printf("multiplication table of %d\n",i);
printf("\n\n");
}
}
Sometime any loop could be placed inside
the other loop
#include<stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf(“d\t",j);
printf(“\n”);
}
}
The output is:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
main(){
int i,j;
for(i=1;i<=5;i++)
{
for(j=5;j>=i; j--)
printf("%d\t", j);
printf("\n");
}}
printf("%d",i);
}
While loop
#include<stdio.h>
main()
{
int loop=0;
while(loop<=10)
{
printf ("%d\n",loop);
++loop;
}
}
Using while for multiplication table from 1 to 10
#include<stdio.h>
main()
{
Int i,j;i=1;
while(i<=10)
{
j=1;
while(j<=10)
{
printf("%d x %d = %d\n",i,j,i*j);
j++;
}
printf("\n\n");i++;
}
}
do while
When developing programs, it sometimes become desirable to have the
test made at the end of the loop rather than at the beginning.
#include<stdio.h>
main()
{
int i;
i=1;
do
{
printf("\n i is:%d",i);
i=i+1;
}
while(i<10);
}
Exercise
• Make a program to print out multiplication
table of 7 using do while.
#include<stdio.h>
main()
{
int i,j;
i=7,j=1;
do
{
printf ("\n %d x %d= %d", i,j,i*j);
j++;
}
while (j<=10 && i<=10 );