C # nested loop


Release date:2023-08-26 Update date:2023-10-13 Editor:admin View counts:347

Label:

C # nested loop

C # allows you to use another loop within one loop, and here are a few examples to illustrate this concept.

Grammar

Nesting in C # for syntax of the loop statement:

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

Nesting in C # while syntax of the loop statement:

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

Nesting in C # do...while syntax of the loop statement:

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

}while( condition );

One thing to note about nested loops is that you can nest any other type of loop within any type of loop. For example, a for loops can be nested in while within the cycle, and vice versa.

Example

The following program uses a nested for loop to find prime numbers from2 to 100:

Example

using System;
namespace Loops
{

   class Program
   {
      static void Main(string[] args)
      {
         /* Definition of Local Variables */
         int i, j;
         for (i = 2; i < 100; i++)
         {
            for (j = 2; j <= (i / j); j++)
               if ((i % j) == 0) break; // If found, it is not a prime number
            if (j > (i / j))
               Console.WriteLine("{0} is a prime number", i);
         }
         Console.ReadLine();
      }
   }
}

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

2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
31 is a prime number
37 is a prime number
41 is a prime number
43 is a prime number
47 is a prime number
53 is a prime number
59 is a prime number
61 is a prime number
67 is a prime number
71 is a prime number
73 is a prime number
79 is a prime number
83 is a prime number
89 is a prime number
97 is a prime number

The prime numbers less than 1000 are:

Image0

Powered by TorCMS (https://github.com/bukun/TorCMS).