Table of contents
1.
Introduction
2.
Why a loop is needed in C#
3.
Categories in Loop statements
3.1.
Entry Controlled loops in C#
3.2.
Exit Controlled loops in C#
4.
For loop
4.1.
Syntax
4.2.
Flowchart
4.3.
Example
5.
foreach loop
5.1.
Syntax
5.2.
Example
6.
While loop
6.1.
Syntax
6.2.
Flowchart
6.3.
Example
7.
Do-while loop
7.1.
Syntax
7.2.
Flowchart
7.3.
Example 
8.
Infinite loops
8.1.
Example
9.
Nested loops
9.1.
Syntax
9.1.1.
Nested for loop
9.1.2.
Nested while loop 
9.1.3.
 
9.1.4.
Nested do-while loop
9.2.
Example
10.
FAQs
11.
Key Takeaways
Last Updated: Nov 21, 2024

Loops in C#

Author Muskan Gupta
4 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In general, the statements execute sequentially. The first statement inside a function executes first, followed by the second, and so on. We use various control structures provided by programming languages for more complicated execution paths. This blog will cover a part of such control structure- loops in C#.

A loop statement lets us execute a statement or a set of statements multiple times, depending upon the result of the condition that needs to be evaluated. The result of the condition must be true for the execution of statements within loops.

Now, we will see each one of for loop, while loop, do-while loop, infinite loop, and nested loop in detail.

Recommended Topic, Palindrome in C# and Ienumerable vs Iqueryable.

Why a loop is needed in C#

Loops in C# are used when a block of code is to be executed multiple times continuously. For example, one has to print "Coding ninjas" 4 times. We can do this by writing the Console.WriteLine statement 4 times as shown in the code below:


using System;

class forLoopDemo
{
	public static void Main()
	{ 
          	Console.WriteLine("Coding ninjas");
          	Console.WriteLine("Coding ninjas");
          	Console.WriteLine("Coding ninjas");
          	Console.WriteLine("Coding ninjas");
	}
}

 

Output:

Coding ninjas
Coding ninjas
Coding ninjas
Coding ninjas

 

While in a loop, the same task is just a few lines away and not even tiring. You will see further in this article that we can get the same output using a loop very quickly. Even the number of times we want to print the "Coding ninjas" changes just by changing the condition in the loop. 

Categories in Loop statements

There are mainly two categories in loop statements:-

Entry Controlled loops in C#

The loop statements in which conditions that need to be tested as true for the execution of the loop are present at the beginning of the loop body are called entry-controlled loops in C#, for loop and while loop is the loops in C# called entry control.

Exit Controlled loops in C#

The loop statements in which conditions that need to be tested as true for the execution of the loop are present at the end of the loop body are called exit-controlled loops in C#. The do-while loop is exit-controlled. As the condition is present at the end, the loop body must be evaluated at least one time.

For loop

For loop is preferred when we know the exact number of iterations already. The variable initialization of loop, testing of executing condition, and the increment/decrement of variable is done in the same line in for loop, giving us the advantage of a shorter and easy way to debug structure of loop efficiently.

Syntax

for ( loop variable initialization ; testing condition ; increment/decrement) { 
	// statement to be executed
}

Flowchart

                             For-loop Flowchart 

Following are the terms used in the flowchart with their explanations:

  1. Initialization: The variable controlling the loop body is initialized in this part. This is the starting point of the loop. We can use either a declared variable or declare a new one, local to loop only. It is evaluated only at the time when the for loop starts.
  2. Test Condition: It is used for a testing condition responsible for executing the loop body. It must return a boolean value true/false. If it returns true, then the only loop is executed. If it returns false, control will be out of the loop, and thus the for loop ends.
  3. Update Expression: It is done in the loop variable according to its requirement. Then, the control again shifts to the testing condition.

Example

The code shown below prints “Coding ninjas” 4 times using a for loop.

using System;

class forLoopDemo
{
	public static void Main() {
		// For loop begins when x=1 and runs till x <=4
		for (int x = 1; x <= 4; x++)
			Console.WriteLine("Coding ninjas");
	}
}

 

Output:

Coding ninjas
Coding ninjas
Coding ninjas
Coding ninjas

 

foreach loop

There is one more type of loop in C#, the for_each loop. It accepts a function that executes each of the elements in the container. It improves the code readability and overall performance of the code. This loop is defined in the "algorithm" header file.

Syntax

foreach(dataType variableName in collectionVariable) {
    // Statements that are to be executed
}

Example

This code prints all the elements present in the array "arr" using a for each loop.

using System;
  
class CN {
  
    // Main Method
    static public void Main() {
        // Creating an array
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        //Printing the statement
        Console.WriteLine("Print array:");

        // foreach loop begins which is going to run till the last element of the array
        foreach(int items in arr)
        {
            Console.WriteLine(items);
        }
    }
}

 

Output 

1
2
3
4
5
6
7
8
9
10

While loop

A while loop statement in C# executes the given set of target statements repeatedly until the given condition remains true. Testing of the condition is done before executing the loop body.

Syntax

while(condition is true){
	Statement();
	Statement();
	Statement();
	.
	.
	.
	Statement();
}

Flowchart

                  While-loop Flowchart 

Test Condition: It is used for a testing condition responsible for executing the loop body. It must return a boolean value true/false. If it returns true, then the only loop is executed. If it returns false, control will be out of the loop, and thus the while loop ends. The critical point of the while loop is that the loop might never run. When the result of testing conditions comes false, the loop body is skipped, and the first statement after the while loop is run. 

Following is the term used in the flowchart with their explanations:

Example

The code shown below prints "Coding is love" 4 times using a while loop.


// C# program to illustrate while loop
using System;

class whileLoopDemo
{
	public static void Main()
	{
		int x = 1;

		// Exit when x becomes greater than 4
		while (x <= 4)
		{
			Console.WriteLine("Coding is love");

			// Increment the value of x for next iteration
			x++;
		}
	}
}

 

Output

Coding is love
Coding is love
Coding is love
Coding is love

Do-while loop

In contrast to while and for loops in C#, in which testing of the condition is done at the start of the loop body, the do-while loop tests the condition at the end of the loop. This ensures that the loop body must be executed at least one time.

Syntax

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

Flowchart

                                           Do-while-loop flowchart 

Here, the conditional expression is present at the end of the loop, so the loop executes one time before the condition results, true or false. If the test condition is true, the control flow comes back up, and the loop body executes again. This process repeats until the testing condition returns false.

Example 

The code shown below is printing "Coding Ninjas" using a do-while loop. Since, in a do-while loop, the statements execute at least once even if the given condition is false. So, even if 21<20 is false, "Coding Ninjas" is printed once. 

// C# program to illustrate do-while loop
using System;

class dowhileloopdemo
{
	public static void Main()
	{
		int x = 21;
		do
		{
			// The line will be printed even if the condition is false
			Console.WriteLine("Coding Ninjas");
			x++;
		}while (x < 20);
	}
}

 

Output 

Coding Ninjas

Infinite loops

The loops in C# in which the testing condition never returns false as a result and thus tend to execute the statements in the loop's body forever(infinite times) until an external force is used to end it is known as infinite loops. The for loop is generally used for this activity. As none of the three expressions that can form the for loop are required, we can make an infinite loop by leaving the conditional expression empty.   

Example

The code shown below is printing "This will go far and beyond" infinite times since there is no specific condition given in for-loop, so it will assume that the condition is true.


// C# program to demonstrate infinite loop
using System;

class infiniteLoop
{
	public static void Main()
	{
		// The statement will be printed infinite times
		for(;;)
			Console.WriteLine("This will go far and beyond.");
	}
}

 

When the conditional expression is not present, it is assumed to be true. We may have an initialization and incremental expression, but the for(;;) is generally constructed to signify an infinite loop.

 

Output

This will go far and beyond.
This will go far and beyond.
This will go far and beyond.
This will go far and beyond.
This will go far and beyond.
..........
..........

Nested loops

When the loops in C# are present inside the other loops, they are known as nested loops. C# allows using one loop inside another loop. The following section shows a few examples to illustrate the concept.

Syntax

The syntax for the various loops are as follows:-

Nested for loop

for ( initialization; condition; increment/decrement ) {
  for ( initialization; condition; increment/decrement ) {
      statement(s);
  }
  statement(s);
}

 

Nested while loop 

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

 

Nested do-while loop

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

A final note on the nesting loop is that we can put any loop inside another loop. For example, a for loop can be present inside a while loop or vice versa.

Example

The code below prints "Coding is love" once.

using System;

class nestedLoops
{
	public static void Main()
	{
	// Loop within loop printing Coding is love
	for(int i = 2; i < 3; i++)
		for(int j = 1; j < i; j++)
			Console.WriteLine("Coding is love");
	}
}

 

Output

Coding is love

The code shown above is printing "Coding is love" once. This happens because the outer loop initiates with i=2, and then the inner loop executes. The inner loop starts with j=1, and "Coding is love" gets printed. After that, j increments to j=2, but j<i becomes false (2<2 is false). So, the inner loop stops. After that, i increments i=3, but the condition i<3 becomes false(3<3 is false). So, the outer loop also stops, and we get the output.

Related Article: Singleton Design Pattern C#

FAQs

  1. Give an example of an exit controlled loop?
    do-while loop is an example of an exit controlled loop.
     
  2. Is any non-zero integer in the place of conditional expression considered true or false?
    Any non-zero integer in the place of conditional expression is considered as true.
     
  3. Which loop is preferred for forming an infinite loop? 
    for loop [for(;;)] is preferred for forming an infinite loop.
     
  4. Why do-while loop executes at least once even when the test condition returns false?
    In a do-while loop, the conditional expression is present at the end of the loop, so the loop executes one time before the condition is tested, true or false.
     
  5. Can we put a while loop inside for the loop to form a nesting loop?
    Yes, we can put a while loop inside for loop to form a nesting loop.
     
  6. How can we add multiple initializers in the for loop?

To add multiple initializers in the for loop, initializers are separated with commas. For example,

for (int i = 0, j = 0; i+j < 10; i++, j++) { 
	Console.WriteLine("i: {0}, j: {1} ", i,j); 
}

Key Takeaways

In this article, we have extensively discussed the concepts of Loops in C#, its categories along with example codes and flowchart, and some frequently asked questions.

We hope that this blog has helped you enhance your knowledge regarding loops in C# and if you would like to learn more, check out our articles on introduction-to-C#. Do upvote our blog to help other ninjas grow. Happy Coding!

Also Read: Four Pillars of OOPS

Live masterclass