Close
Close

Loops in C#


Playing with loops makes programming fun. Before we try to understand loops, you should have a concrete knowledge of all the previous topics of C#. If not, go through the previous topics first.

Suppose, we have to print the first 10 natural numbers.

One way to do this is to print the first 10 natural numbers individually using Console.WriteLine. But what if you are asked to print the first 100 natural numbers! You can easily do this with the help of loops.

Broadly classifying, there are three types of loops in C# which are:

  1. while loop
  2. for loop
  3. do...while loop

C# while Loop


Let's look at the syntax of while loop first.

while(condition)
{
    statement(s)
}

while loop checks whether the condition written in ( ) is true or not. If the condition is true, the statements written in the body of the while loop i.e., inside the braces { } are executed. Then again the condition is checked, and if found true, again the statements in the body of the while loop are executed. This process continues until the condition becomes false.

while loop in C#

An example will make this clear.

using System;

class Test
{
static void Main(string[] args)
{
  int n = 1;

  while(n <= 10)
  {
      Console.WriteLine(n);
      n++;
  }
}
}
Output
1
2
3
4
5
6
7
8
9
10

In our example, firstly, we assigned a value 1 to a variable n.

while(n <= 10) → checks the condition n <= 10. Since the value of n is 1 which is less than 10, the statements within the braces { } are executed.

The value of n i.e. 1 is printed and n++ increases the value of n by 1. So, now the value of n becomes 2.

Now, again the condition is checked. This time also n <= 10 is true because the value of n is 2. So, again the value of n i.e., 2 gets printed and the value of n will be increased to 3.

When the value of n becomes 10, again the condition n <= 10 is true and 10 gets printed for the tenth time. Now, n++ increases the value of n to 11.

This time, the condition n <= 10 becomes false and the loop terminates.

Quite interesting. Isn't it!

while loop animation in C#

Let's see one more example of while loop.

using System;

class Test
{
static void Main(string[] args)
{
  bool choice = true;

  while(choice)
  {
      int a;

      Console.WriteLine("Enter a number to check if it is even or odd");

      a = Convert.ToInt32(Console.ReadLine());

      if(a%2 == 0)
          Console.WriteLine("Even");
      else
          Console.WriteLine("Odd");

      Console.WriteLine("Want to check more numbers? n for no");

      if(Console.ReadLine() == "n")
          choice = false;
  }

  Console.WriteLine("I hope you checked all your numbers");
}
}
Output
Enter a number to check if it is even or odd
2
Even
Want to check more numbers? n for no
y
Enter a number to check if it is even or odd
4
Even
Want to check more numbers? n for no
y
Enter a number to check if it is even or odd
5
Odd
Want to check more numbers? n for no
n
I hope you checked all your numbers

The loop will run until the value of choice becomes false. So, for the first time, it will run since the value of choice is true. Then it will perform the codes inside the loop. At last, it will ask the user whether he wants to check more or not. This can change the value of variable choice and may terminate the loop.

Initially, the value of choice was true, so the condition of while got satisfied and codes inside it got executed. We were asked to give the value of choice and we gave 'y' again. Things repeated and after that, we gave choice a value of 'n' which lead to change the value of choice to false. Now, the condition of while was not satisfied and the loop terminated.

C# for Loop


Another type of loop is for loop.

Let's go to our first example in which we printed the first 10 natural numbers using while loop. We can also do this with for loop.

Let's look at the syntax of for loop first.

for(initialization; condition; propagation)
{
    statement(s)
}

It is also similar to the while loop. The statements inside for loop are also repeated till the condition of for(initialization; condition; propagation) is satisfied. The propagation is executed at the end of each iteration. It is similar to writing a statement at the last of while loop because it will also be executed at the end of each iteration. initialization is executed only once and before starting the loop. It is similar to putting statement above the while loop which will be executed before starting the loop.

comparing for and while loop in C#

Let's take an example first.

using System;

class Test
{
static void Main(string[] args)
{
  int n;

  for(n=1; n<=10; n++)
  {
      Console.WriteLine(n);
  }
}
}
Output
1
2
3
4
5
6
7
8
9
10

n=1 → This step is used to initialize a variable and is executed first and only once. Here, n is assigned a value 1.

n<=10 → This is a condition which is evaluated. If the condition is true, the statements written in the body of the loop are executed. If it is false, the statements just after the for loop will be executed. This is similar to the condition we used in 'while' loop which was being checked again and again.

n++ → This is executed after execution of the codes in the body of the for. In this example, the value of n increases by 1 every time the codes in the body of the for loop execute. There can be any expression here which you want to run after every iteration of the loop.

In the above example, firstly, n=1 assigns a value 1 to n.

Then the condition n<=10 is checked. Since the value of n is 1, therefore the code in the body of for loop is executed and thus the current value of n i.e., 1 gets printed.

Once the codes in the body of for loop are executed, step n++ is executed which increases the value of n by 1. So now the value of n is 2.

Again the condition n<=10 is checked which is true because the value of n is 2. Again codes in the body of for loop are executed and 2 gets printed and then the value of n is again incremented.

When the value of n becomes 10, the condition n <= 10 is true and 10 gets printed. Now, when n++ increases the value to n to 11, the condition n<=10 becomes false and the loop terminates.

We can also skip {} if we have only a single statement for the loop similar to if and else. The first statement after the loop will be considered as part of the loop.
using System;

class Test
{
static void Main(string[] args)
{
  int n;

  for(n=1; n<=10; n++)
      Console.WriteLine(n);
}
}
Output
1
2
3
4
5
6
7
8
9
10

You can see that we have skipped {} in the above example because we have only one statement to put inside the loop.

Let's see the example of adding 10 numbers.

using System;

class Test
{
static void Main(string[] args)
{
  int sum = 0, n;

  for(int i=0; i<10; i++)
  {
      Console.WriteLine("Enter Number");
      n = Convert.ToInt32(Console.ReadLine());

      sum = sum+n;
  }

  Console.WriteLine($"Sum is {sum}");
}
}
Output
Enter number
4
Enter number
3
Enter number
10
Enter number
3
Enter number
5
Enter number
5
Enter number
1
Enter number
8
Enter number
9
Enter number
2
Sum is 50

Initially, the value of the variable sum is 0.

In the first iteration, the value of n is 4 and thus the value of sum becomes 4 since sum = sum + n (i.e. sum = 0 + n).

In the second iteration, the value of sum is 4 and we entered 3 as the value of n. Therefore, the expression sum = sum + n gets evaluated as sum = 4 + 3, thus making the value of sum as 7.

In this way, this loop will add all the 10 numbers entered by the user.

There are other ways also to write a program of for loop.

The first example of for loop in which we printed the first 10 natural numbers can also be written in other ways which are:

int n = 1;
for( ; n <= 10; n++)
{
    Console.WriteLine(n);
}

Another way is shown below.

int n;
for( n = 1; n <= 10; )
{
    Console.WriteLine(n);
    n++;
}

It means that we can also write the for loop by skipping one or more of its three statements (initialization, condition, propagation) as done above.

C# do while Loop


do while loop is another kind of loop. This is just like while and for loop but the only difference is that the code in its body is executed once before checking the condition.

Syntax of do...while loop is:

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

Consider the same example of printing the first 10 natural numbers for which we wrote programs using while and for loops. Now, let's write its program using do while loop.

using System;

class Test
{
static void Main(string[] args)
{
  int n = 1;

  do
  {
      Console.WriteLine(n);
      n++;
  }while(n<=10);
}
}
Output
1
2
3
4
5
6
7
8
9
10

Let's understand this code.

At first, the statements inside the body of loop (i.e., within the braces { } following do) are executed. This will print the value of n i.e., 1 and n++ increments the value of n by 1. So now, the value of n becomes 2. Take a note that the first iteration happened without checking the condition of the loop.

Once the code inside the braces { } is executed, the condition n <= 10 is checked. Since the value of n is 2, so the condition is satisfied.

Again the code inside the body of loop is executed and the value of n becomes 3. Similarly, when the value of n is 10 and 10 is printed, n++ increases the value of n to 11. After this, the condition becomes false and the loop terminates.

C# Nesting of Loops


Like if/else we can also use one loop inside another. This is called nesting of loops. See this example to make it clear.

using System;

class Test
{
static void Main(string[] args)
{
  for(int i=12; i<=14; i++)
  {
      Console.WriteLine($"Table of {i}");

      for(int j=1; j<=10; j++)
      {
          Console.WriteLine($"{i}*{j} = {i*j}");
      }
  }
}
}
Output
Table of 12
12*1 = 12
12*2 = 24
12*3 = 36
12*4 = 48
12*5 = 60
12*6 = 72
12*7 = 84
12*8 = 96
12*9 = 108
12*10 = 120
Table of 13
13*1 = 13
13*2 = 26
13*3 = 39
13*4 = 52
13*5 = 65
13*6 = 78
13*7 = 91
13*8 = 104
13*9 = 117
13*10 = 130
Table of 14
14*1 = 14
14*2 = 28
14*3 = 42
14*4 = 56
14*5 = 70
14*6 = 84
14*7 = 98
14*8 = 112
14*9 = 126
14*10 = 140

When the first for loop is executed, the value of i is 12 and "Table of 12" gets printed.

Now coming to the second loop, the value of j is 1 and thus 12*1 = 12 gets printed.

In the second iteration of the inner for loop, while the value of i is still 12, the value of j becomes 2 and thus 12 * 2 = 24 gets printed.

In the last iteration of the inner for loop, the value of i is still 12 and the value of j becomes 10, thus printing 12 * 10 = 120.

Now after all the iterations of the inner for loop are complete, there will be the second iteration of the outer for loop increasing the value of i to 13 and printing "Table of 13". Again the inner for loop will be started with i equals 13.

We can use any loop inside any other loop according to the requirement. In the above example, we used one for loop inside another.

C# Infinite Loop


There may exist some loops which can iterate or occur infinitely. These are called infinite loops. These loops occur infinitely because their condition is always true. We can make an infinite loop by leaving its conditional expression empty (this is one of the many possible ways). When the conditional expression is empty, it is assumed to be true. Let's see an example on how to make a for loop infinite.

using System;

class Test
{
static void Main(string[] args)
{
  for(;;)
      Console.WriteLine("This loop will never end");
}
}
Output
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
...
To terminate an infinite loop, press ctrl + c.

C# Scopes of Variables


Scope of a variable is basically the part of our program where we can access that variable. A variable defined inside a block (inside { }) like for, if, etc. is not available outside the block.

Let's take an example of accessing a variable defined in if block outside it.

using System;

class Test
{
static void Main(string[] args)
{
  if(true) {
    int a = 10;
  }
  Console.WriteLine(a);
}
}
Output
file.cs(10,23): error CS0103: The name `a' does not exist in the current context
Compilation failed: 1 error(s), 0 warnings

As stated above, the variable a defined inside if and we tried accessing it outside it and thus got an error.

Similarly, a variable defined inside any block is invalid outside it.

using System;

class Test
{
static void Main(string[] args)
{
  {
    int a = 10;
  }
  Console.WriteLine(a);
}
}
Output
file.cs(10,23): error CS0103: The name `a' does not exist in the current context
Compilation failed: 1 error(s), 0 warnings

In this example also, the variable a is only available inside its block (inside {} enclosing it).

Let's take one more example.

using System;

class Test
{
static void Main(string[] args)
{
  { //outer block
    int a = 10;
    { //inner block
      Console.WriteLine(a);
    }
  }
}
}
Output
10

In this example, the blocks are nested. However, the inner block is also the part of the outer block also. So, the variables of the outer block are accessible inside the inner block.


Ask Yours
Post Yours
Doubt? Ask question