You are on page 1of 11

CS112 - PROGRAMMING FUNDAMENTAL

Lecture # 20 – Iterative Control in C


Syed Shahrooz Shamim
Junior Lecturer,
CS Department, UIT
For Loop
The general format for a for loop

1 2 3
for (Initialization_action; Condition; Condition_update)
{
statement_list;
}

Factorial of n is n(n-1)(n-2)...21
int n,f=1;
scanf(“%d”,&n);

for (i=2; i<=n; i++)


{
f *= i;
}

Printf(“The factorial of %d is %f”, n, f);


Compare: for and while

1 2 3
for (Initialization_action; Condition; Condition_update)
{
statement_list;
}

i=2;
while (i<=n)
int n,f=1; {
scanf(“%d”,&n); f *= i;
i++;
for (i=2; i<=n; i++) }
{
f *= i;
}

Printf(“The factorial of %d is %f”, n, f);


Compare: for and while

int n,i; int n,i;

n = 100; n = 100;
i = 1;

for (i=1; i <= n; i++) v.s. while (i <= n)


{ {
statement_list; statement_list;
} i++;
}
Break in a for loop
The break statement in a for loop will force the program to jump
out of the for loop immediately.

The continue statement in a for loop will force the program to


update the loop condition and then check the condition immediately.

for (Initialization_action; Condition; Condition_update)


{
statement_list;
}
Nested loops (loop in loop)

Scanf(“%d”,&a);
Scanf(“%d”,&b);
for (int i = 0; i < a; i++)
{
for (int j=0; j<b; j++)
{
printf(“*”);
}
printf(“\n”); b
}
*************
a *************
*************
*************
Nested loops (loop in loop)
int a,b;
Scanf(“%d”,&a);
Scanf(“%d”,&b);

for (int i = 0; i < a; i++)


{
for (int j=0; j<b; j++)
{
if (j > i)
b
break;
printf(“*”); *
}
printf(“\n”); a **
} ***
****
Nested loops (loop in loop)
int a,b;
Scanf(“%d”,&a); if (j > i) break;
Scanf(“%d”,&b);

for (int i = 0; i < a; i++)


{ for (int j=0; j<b && j <
<=i;
i; j++)
{
printf(“*”);
}
printf(“\n”);
} b
*
a **
***
****
Nested loops (loop in loop)

int a,b;
Scanf(“%d”,&a);
Scanf(“%d”,&b);

for (int i = 0; i < a; i++)


{
for (int j=0; j<b; j++)
{
if (j < i) b
printf(“ ”);
else *************
printf(“*”); a ************
} ***********
printf(“\n”); **********
}
Nested loops (loop in loop)
int a,i,j;
scanf("%d",&a);

for (i = 0; i < a; i++) {


for (j=0; j<a; j++) {
if (j < a-i) *
printf(" ");
else printf("*"); ***
} *****
*******
for (j=0; j<a; j++) { *********
if (j > i) break; ***********
printf("*");
}
printf("\n");
}

You might also like