Professional Documents
Culture Documents
Lecture 10
Lecture 10
CS-1001
Lecture 11
Outlines
• Nested loops
• Nested for, while and do while
• Examples of nested loops
• Loop control statements
– Break
– Continue
– goto
Nested Loops
• C programming language allows us to use one
loop inside another loop
• You can put any type of loop inside any other
type of loop. For example, a for loop can be
inside a while loop or vice versa
• General syntax
– Loop (…)
– Loop(…)
– statement/s
– End Loop
– End Loop
Nested for loop
• Inserting for loop within another for loop
• Syntax
for(init ; condition; update)
{ for(init ; condition;
update) {
statement/s;
}
statement/s;
}
Nested while loop
• Inserting a while loop inside another while loop
• Syntax
– while(condition)
–{
– while(condition)
– {
– statement(s);
– }
– statement(s);
–}
Nested do while loop
• Nesting a do while loop inside another one
• Syntax
do
{
statement(s);
do
{
statement(
s);
}while( condi
tion );
}while( conditio
n );
Nested loop example (nestedLoop.c)
#include <stdio.h>
int main ()
{
// local variable definition
int i=0, j=0;
return 0;
}
Nested loop example (nestedLoop.c)
#include <stdio.h>
int main ()
{
// local variable definition
int i=0, j=0;
return 0;
}
Nested loop example (nestedLoop.c)
#include <stdio.h>
int main ()
{
// local variable definition
int i=0, j=0;
return 0;
}
Example (nestedLoop2.c)
Creating a 10x10 identity matrix
#include <stdio.h>
int main ()
{
// local variable definition
int i=0, j=0;
return 0;
}
Loop control statements
• Loop control statements change execution of
a loop from its normal sequence
• When execution leaves a scope, all automatic
objects that were created in that scope are
destroyed
Break statement
• Two usages
– Terminate a loop prematurely
– Terminate a case in the switch statement
• In case of nested loops, if the break statement
is in the inner loop, it will stop the execution
of the inner loop and start executing the next
line of code of the outer loop.
Example (primes.c)
#include<stdio.h>
int main(){
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
flag = 1;break;
}
}
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0; }
Example (break.c)
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
Output
value of a: 10
/* while loop execution */
value of a: 11
while( a < 20 )
value of a: 12
{
printf("value of a: %d\n", a);
value of a: 13
a++; value of a: 14
if( a > 15) value of a: 15
{
/* terminate the loop using break statement */
break;
}
}
return 0;
}
Continue statement
• Works like the break statement
• Instead of forcing termination, however,
continue forces the next iteration of the loop
to take place, skipping any code in between.
Example (continue.c)
#include <stdio.h>