Objective
Studying loops. For loops, nested for loops, while loops, nested while loops, do while loops, nested do
while loops. Studying loops with cross combination.
Theory
do
for while
while
initialization; initialization;
while(check range) do
for(initialization ; check range ; iteration)
{
{ {
body body
body
} iteration;
iteration;
}
} while(check range)
Example: This table below shows nested loops. All the three programs have same output.
This program of while loops takes continuous input until enter key is pressed.
Program Output
#include<stdio.h>
#include<conio.h>void
main(void)
{ clrscr();
Type any sentence
int a=0; Iqra University
printf("Type any sentence\n"); Total Characters typed = 15
while(getche()!='\r')
a++;
printf("\nTotal Characters typed = %d",a); getch();
Exercise
Carefully observer the following program and write output with reasons.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h> #include<stdio.h>
void main(void) #include<conio.h>
{ void main ()
clrscr(); {
for(int a=0;a<=12;a++); int a=0;
printf("%d x 2 = %d\n",a,a*2); while(c<=12)
getch(); } {
printf("\n%d*2=%d",a,a*2);
a++;
getch();
#include<stdio.h> Write the output for the program on left
#include<conio.h> #include<stdio.h>
void main(void) #include<conio.h>
{ void main(void)
clrscr(); {
for(int a=0;1 ;a++); int a=0;
printf("%d x 2 = %d\n",a,a*2); while(a<=1)
getch(); } {
printf("\n%d*2=%d",a,a*2);
a++;
getch();
}
#include<stdio.h> Write the output for the program on left
#include<conio.h> #include<stdio.h>
void main(void) #include<conio.h>
{ clrscr(); void main(void)
int a=0; {
while(0) int a=0;
{ while(a<=0)
printf("%d x 2 = %d\n",a,a*2); {
a++; printf("\n%d*2=%d",a,a*2);
} getch(); a++;
} }
getch();
#include<stdio.h> Write the output for the program on left
#include<conio.h> #include<stdio.h>
void main(void) #include<conio.h>
{ clrscr(); void main(void)
int a=0,b; {
while(a<=3); int a=0,b=0;
{ while(a<=3)
b=0; {
while(b<=3); while(b<=3)
{ {
printf("\n%d%d",a,b);
printf("%d%d\t",a,b);
b++;
b++;
}
}
printf("\n");
printf("\n");
a++;
a++;
}
} getch();
getch();
]
}