LogIn
I don't have account.

while loop in C#

DevSniper
154 Views

while(condition)
{  
   // code block
}
  • while loop
  • Infinite while Loop
  • nested while loop
  • while loop is used to execute a block of code several times
  • while loop is an entry control loop it verifies condition before executing of the code block.

while Loop

Example 1
using System;

class Program
{
    static void Main()
    {
        int i=3;
        while(i<10) {
            Console.WriteLine(i);
            i++;
        }
    }
}
3
4
5
6
7
8
9
Example 2
using System;

class Program
{
    static void Main()
    {
        int i=10,n=50;
        while(i<n) {
            if(i%5==0)
                Console.WriteLine(i);
            i++;
        }
    }
}
10
15
20
25
30
35
40
45

Infinite while Loop

if we define a condition that never becomes false, loop become Infinite Loop

Example
while(true) 
{
   // Code block
}
OR
while(2<5) 
{
   // Code block
}
OR
int i=5;
while(i<10) 
{
   Console.WriteLine(i);
}
Nested While Loop

if we place one loop inside other while loop this is called nested while loop. inner while loop executed fully for every outer while loop execution.

using System;

class Program
{
    static void Main()
    {
        int i=1;
        while(i<=2 ) {
            Console.WriteLine($"Inside Outer loop i : {i}");
            int j=1;
            while( j<=3 ) {
                Console.WriteLine($"\tinside inner loop i :- {i} and j : {j}");
                j++;
            }
            i++;
        }
    }
}
Inside Outer loop i : 1
	inside inner loop i :- 1 and j : 1
	inside inner loop i :- 1 and j : 2
	inside inner loop i :- 1 and j : 3
Inside Outer loop i : 2
	inside inner loop i :- 2 and j : 1
	inside inner loop i :- 2 and j : 2
	inside inner loop i :- 2 and j : 3