In for loop, we already know how many times code inside loop will be executed based on conditions, but in "while" loop, code inside the loop will be excuted until a particular condition is true.
So While loop can be used when number of iterations of a code is unknown.
Syntax for while loop
while(condition)
{
//code to be executed
}
Example:
using System;
public class WhileLoopProgram
{
public static void Main()
{
int i;
Console.WriteLine("How many times you want to print i?");
i = Convert.ToInt32(Console.ReadLine());
while(i > 0)
{
Console.WriteLine("Value of i="+i);
i--;
}
}
}
Output:
How many times you want to print i?
10
Value of i=10
Value of i=9
Value of i=8
Value of i=7
Value of i=6
Value of i=5
Value of i=4
Value of i=3
Value of i=2
Value of i=1
In the above code, we are getting value of "i" from user, by using Console.ReadLine()
which is used to read value entered by user. But as this value is in string we are converting value to "int
" using Convert.ToInt32()
method.
Using While loop we are printing values of i until the value of "i" is not equal to 0 or you can say it prints until it's value is greater than 0.
Another simple example of while loop
public static void Main()
{
int num= 1;
while (num < 10)
{
Console.WriteLine(num++);
}
}
Output:
1
2
3
4
5
6
7
8
9
In while loop we can make loop for infinite by placing true inside the condition
while (true) // Executes forever
{
Console.WriteLine("Never Stop!");
}
Next example, will never execute
while (false) // Never executes
{
Console.WriteLine("Never execute");
}
You can place while loop inside another loop, just like for loop, here is the example for it
using System;
public class NestedWhileLoopProgram
{
public static void Main()
{
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
Console.WriteLine(i+" "+j);
j++;
}
Console.WriteLine("End of iteratoin number "+i +" of while loop");
i++;
}
}
}
Output:
1 1
1 2
1 3
End of iteratoin number 1 of while loop
2 1
2 2
2 3
End of iteratoin number 2 of while loop
3 1
3 2
3 3
End of iteratoin number 3 of while loop