Loops in C#

If you want to execute your code repeatedly certain number of times or until a certain condition is met, you can use C# iterative statements which are also known as loops.

There are three types of loops in C#.

  • For loop
  • While loop
  • Do-While loop

For Loop

For loop is usually used when you already know the number of times you want to repeat the execution of your code. For instance if you want to print the table of 7, you know that you will have to repeat your multiplication logic 10 times. Consider following example:

using System;

namespace CSharpTutorials {
    class ForLoop {
        static void Main(string[] args) {
            for (int i = 1; i < 11; i++)  {
                Console.WriteLine("7 x " + i + " = " + 7 * i);
            }
            Console.ReadKey();
        }
    }
}

Download the above code

For loop starts with the keyword “for”. It has three parts: Initiation statement, test condition, and increment statement which are separated by a semicolon. Here i=1 is initiation statement, i<11 is test condition and i++ is increment statement. For loop keeps on executing until the test condition returns false.

While loop

While loop keeps on executing until a certain condition is met. In the next example the table of 7 is printed using while loop.

using System;

namespace CSharpTutorials {
    class WhileLoop {
        static void Main(string[] args) {
            int i = 1;

            while ( i < 11) {
                Console.WriteLine("7 x " + i + " = " + 7 * i);
                i++;
            }
            Console.ReadKey();
        }
    }
}

Download the above code

In while loop the initiating statement is written before the while loop and the increment condition is written inside the loop. During each execution the test condition is checked and if it returns true, the code inside the loop is executed.

Do-While loop

Do-While loop is similar to while loop but in Do-While loop the test condition is evaluated at the end of the loop which means that the code inside the loop is executed at least once. Let us see how the table of 7 can be printed on console screen via do-while loop.

using System;

namespace CSharpTutorials {
    class DoWhileLoop {
        static void Main(string[] args) {
            int i = 1;
			do {
                Console.WriteLine("7 x " + i + " = " + 7 * i);
                i++;
            }
            while (i < 11) ;

            Console.ReadKey();
        }
    }
}

Download the above code

It can be seen in the above code that the while statement has been appended at the end of the loop and test condition is being executed there. At the start of the loop, the keyword “do” specifies that it is a do-while loop.

<<< Access Modifiers in C#Structures in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .