Loops

Loops

In programming, it is often desired to execute certain block of statements for a specified number of times. A possible solution will be to type those statements for the required number of times.

  • However, the number of repetition may not be known in advance (during compile time) or

  • Repetitions maybe large enough (say 10000).

  • The best solution to such problem is loop.

  • There are 3 types of loops available in C#: for, while and do while

  • The do while loop is the same as while loop except that it executes the code block at least once

For Loop

The Syntax for a for loop is:

for (initialization; condition; iterator)
{
	// body of for loop
}

How for loop works?

  • C# for loop has three statements: initialization, condition and iterator.

  • The initialization statement is executed at first and only once. Here, the variable is usually declared and initialized.

  • Then, the condition is evaluated. The condition is a boolean expression, i.e. it returns either true or false.

  • If the condition is evaluated to true: The statements inside the for loop are executed.

  • Then, the iterator statement is executed which usually changes the value of the initialized variable.

  • Again the condition is evaluated. The process continues until the condition is evaluated to false.

  • If the condition is evaluated to false, the for loop terminates.

Example

The following code prints the output shown:

for (int i=1; i<=5; i++)
{
  Console.WriteLine("C# For Loop: Iteration {0}", i);
}
C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

Exercise

Print the multiples of 4 between the numbers 30 and 50, both inclusive?

Hint: You can use modulus operator % and == operator

Expected output

32 36 40 44 48
using System;

class Program
{
    static void Main()
    {
        for(){
            if()
                Console.Write(i + " ");
        }
    }
}

Exercise

Print the sum of first 10 natural numbers

Expected output:

Sum of first 10 natural numbers = 55
using System;

class Program
{
	public static void Main()
	{
		int n = 10,sum = 0;

		for ()
		{			
			sum += i;
		}

		Console.WriteLine("Sum of first {0} natural numbers = {1}", n, sum);
	}
}

While loop

Unlike for loops, while loops do not allow you to declare or assign the variable used in the conditions. The while keyword is used to create while loop in C#.

The syntax for while loop is:

while (test-expression)
{
	// body of while
}

Example

int i=1;
while (i<=5)
{
  Console.WriteLine("C# For Loop: Iteration {0}", i);
  i++;
}

When we run the program, the output will be:

C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

Do while loop

The do and while keyword is used to create a do-while loop. It is similar to a while loop, however there is a major difference between them:

In while loop, the condition is checked before the body is executed. So it will execute at least once

The syntax for do...while loop is:

do
{
  // body of do while loop
} while (test-expression);

Example

int i = 1, n = 5, product;

do
{
  product = n * i;
  Console.WriteLine("{0} * {1} = {2}", n, i, product);
  i++;

} while (i <= 10);

Output

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Continue statement

In C#, we use the continue statement to skip a current iteration of a loop. When our program encounters the continue statement, the program control moves to the end of the loop. It is useful in certain conditions where we no longer want to process anything based on a current condition. It works on all 3 types of loops.

Example

class Program {
    static void Main(string[] args){
      for (int i = 1; i <= 5; ++i{
                
        if (i == 3) {
          continue;
        }

        Console.WriteLine(i);
      }
    }
  }

Output

1
2
4
5

Break statement

In C#, we use the break statement to terminate the loop. As we know, loops iterate over a block of code until the test expression is false. However, sometimes we may need to terminate the loop immediately without checking the test expression. In such cases, the break statement is used.

Example

class Program {
    static void Main(string[] args) {

      for (int i = 1; i <= 5; ++i) {
        
        // terminates the loop
        if (i == 3) {
          break; 
        }
            	
        Console.WriteLine(i);
      }
      	 
      Console.ReadLine();
      
    }
  }

Output

1
2

Last updated