Lec6 (Decission Making& Looping)
Lec6 (Decission Making& Looping)
CONTENT
Test
false
condition Body of the
? loop
true
Body of the
loop
Test
condition
?
GENERAL FORMAT
int main(){
int sum=0,n=1;
while(n>=1)
{
sum=sum+n;
n=n+1;
}
printf(“%d”, sum);
return 0;
}
THE DO-WHILE STATEMENT
GENERAL FORMAT
do
{
body of the loop;
}
int main(){
int sum=0,n=1;
do
{
sum=sum+n;
n=n+1;
}
while(n>=1);
printf(“%d”,sum);
return 0;
}
THE FOR STATEMENT
GENERAL FORMAT
#include<stdio.h>
#include<conio.h>
main(){
int sum=0,a,n;
clrscr();
scanf(“%d”,&n);
for (a=1;a<=n;a++){
sum=sum+a;}
printf(“%d”,sum);
getch();}
ADDITIONAL FEATURES OF FOR LOOP
p=1;
for(n=1;n<=17;n++)
Same as
for(p=1,n=1;n<=17;n++)
NESTING OF FOR LOOPS
When one for statement within another for statement,
then it is called nesting of for loops.
GENERAL FORMAT
for (i=1;i<=5;i++)
{
……………… Outer loop
for (j=1;j<=5;j++)
{
………. Inner loop
}
…..
}
……..
KEY POINT
Example
for(row=1;row<=5;row++)
{
for (column=1;column<=5;column++)
{
y=row*column;
The outer loop controls row
printf(“%d”,y); while inner loop control column.
}
printf(“\n”);
}
JUMPING OUT OF A LOOP
GENERAL FORMAT
break;
KEY POINT
Output:
0
1
2
3
SKIPPING A PART OF A LOOP
Under certain condition it is necessary to skip a part of
the body of the loop. This job can be performed by
continue statement.
GENERAL FORMAT
Continue;
KEY POINTS
Output:
0
1
2
3
5
6
7
8
9
Practice Problem
Output:
0
Only this will appear! Really??
Practice Problem
Output:
0
1
2
3
4
Hurrah! Only this will appear!
Practice Problem
Output:
Sum = 25
PROGRAMS & OUTPUT
1
X=1
PROGRAMS & OUTPUT
1 0 3 2 7 6 13 12 21
X=21