Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Nested Loops

C Nested Loops

C Loops C Loops

C allows one loop to be used inside another; the following examples illustrate this concept.

Syntax

In the C language Nested for loop statement syntax:



for (initialization; condition; increment/decrement)

{

    statement(s);

    for (initialization; condition; increment/decrement)

    {

        statement(s);

        ... ... ...

    }

    ... ... ...

}

Flow diagram:

In the C language Nested while loop statement syntax:



while (condition1)

{

    statement(s);

    while (condition2)

    {

        statement(s);

        ... ... ...

    }

    ... ... ...

}

Flow diagram:

In the C language Nested do...while loop statement syntax:



do

{

    statement(s);

    do

    {

        statement(s);

        ... ... ...

    }while (condition2);

    ... ... ...

}while (condition1);

Flow diagram:

One thing worth noting about nested loops is that you can nest any type of loop inside any other type of loop. For example, a for loop can be nested inside a while loop, and vice versa.

Example

The following program uses a nested for loop to find prime numbers between 2 and 100:

Nested for example

#include

<

stdio.h

int

main

(

)

{

/*

Local variable definition

*/

int

i

,

j

;

for

(

i

=

2

;

i

<

100

;

i

++

)

{

for

(

j

=

2

;

j

<=

(

i

/

j

)

;

j

++

)

if

(

!

(

i

%

j

)

)

break

;

// If found, it is not a prime number

if

(

j

(

i

/

j

)

)

printf

(

"

%d is a prime number

\

n

"

,

i

)

;

}

return

0

;

}

When the code above is compiled and executed, it produces the following result:



2 是质数

3 是质数

5 是质数

7 是质数

11 是质数

13 是质数

17 是质数

19 是质数

23 是质数

29 是质数

31 是质数

37 是质数

41 是质数

43 是质数

47 是质数

53 是质数

59 是质数

61 是质数

67 是质数

71 是质数

73 是质数

79 是质数

83 是质数

89 是质数

97 是质数

Nested while example

#include

<

stdio.h

int

main

(

)

{

int

i

=

1

,

j

;

while

(

i

<=

5

)

{

j

=

1

;

while

(

j

<=

i

)

{

printf

(

"

%d

"

,

j

)

;

j

++;

}

printf

(

"

\

n

"

)

;

i

++;

}

return

0

;

}

When the code above is compiled and executed, it produces the following result:



1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

Nested do-while example

#include

<

stdio.h

int

main

(

)

{

int

i

=

1

,

j

;

do

{

j

=

1

;

do

{

printf

(

"

"

)

;

j

++;

}

while

(

j

<=

i

)

;

i

++;

printf

(

"

\

n

"

)

;

}

while

(

i

<=

5

)

;

return

0

;

}

When the code above is compiled and executed, it produces the following result:



*

**

***

****

*****

C Loops C Loops