Latest web development tutorials

C nested loop

C cycle C cycle

C language allows the use of another loop within a loop below demonstrates several examples to illustrate this concept.

grammar

C languagenested for loop syntax:

for ( init; condition; increment )
{
   for ( init; condition; increment )
   {
      statement(s);
   }
   statement(s);
}

C languagenest while loop syntax:

while(condition)
{
   while(condition)
   {
      statement(s);
   }
   statement(s);
}

C languagenest do ... while loop syntax statements:

do
{
   statement(s);
   do
   {
      statement(s);
   }while( condition );

}while( condition );

About nested loop is worth noting that you can nest any other type of cycle in any type of cycle. For example, a for loop can be nested within a while loop, and vice versa.

Examples

The following program uses a nested for loop to find 2-100 of prime numbers:

#include <stdio.h>
 
int main ()
{
   /* 局部变量定义 */
   int i, j;
   
   for(i=2; i<100; i++) {
      for(j=2; j <= (i/j); j++)
        if(!(i%j)) break; // 如果找到,则不是质数
      if(j > (i/j)) printf("%d 是质数\n", i);
   }
 
   return 0;
}

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

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 是质数

C cycle C cycle