Search Placementyogi.com
 

For Loop in C#.NET

The for loop in C# allows us to execute a set of statements a specific number of times.

Syntax of for loop in C#:

for(initialization;condition;iteration)
{
	//body
}

If there is just one statement in the body , the braces are not required.

For Loop Control Flow in C#

Control Flow of for loop in C#:

  1. The initialization statement is executed first.It declares and initializes the value of the "loop control variable" which acts as the counter of the for loop. It executes only once at the beginning of the for loop.
  2. The condition statement is executed next and tests the value of the loop control variable and decides whether the body of the for loop can be executed. It can only be a boolean expression. If the condition evaluates to true , the body is executed otherwise the loop terminates and the statement after the for loop is executed.
  3. The body of the for loop is executed next.
  4. Once the control finishes executing the last statement of the body, the control goes to the iteration statement. It updates/modifies the value of the loop control variable/ counter and prepares for the next iteration.
  5. Then the control again enters the condition statement and checks whether the updated control variable still satisfies the condition. 

Thus, the steps 2, 3 and 4 are executed in a loop until the condition evaluates to false.

Example of for loop in C#:

public class ForLoop
{
	public static void main(String[] args)
	{
		for(int i=5;i<10;i++)
		{
			Console.WriteLine("i="+i);
		}
		Console.WriteLine("After for loop");
} }

Output:

i=5

i=6

i=7

i=8

i=9

After for loop

 

Explanation: 

Notice that the variable i is declared inside the initialization statement of the for loop. This means that the scope of "i" is only inside the for loop.

First, i is initialized to 5. Then i<10 condition is tested and since it is true, the control enters the body.

The statement Console.WriteLine is executed and i=5 is printed.

Then, the iteration statement (i++) is executed and increments the value of i to 6.

This updated value of i is tested again in the condition statement (i<10) , since 6<10 is true, the control again enter the body and prints i=6.

This goes on, till i=9 is printed.

When the control enters the iteration statement this time, i becomes 10.

The condition is tested and i<10 becomes false.

The control comes out of the for loop and "After for loop" is printed!

Try to go through the above explanation once more to grasp the whole concept thoroughly. This is one of the most important concept and many interview questions are asked from for loop based on the control flow.

Variations of for loop in C#

The initialization statement, condition statement and iteration statement are not compulsory, and they can be kept empty.

We can rewrite the above program in these way also:

Variation 1: Without the initialization and iteration statement
public class ForLoop
{
	public static void main(String[] args)
	{
		int i=5;
		for(;i<10;)
		{
			Console.WriteLine("i="+i);
			i++;
		}
		Console.WriteLine("After for loop");
	}
}

In the above program, we have intentionally kept the initialization and iteration part empty. But, T achieve this, we had to write the initialization statement before the for loop and had to increment the counter inside the body of the loop.

Variation 2: Without the Condition Statement

In the following program, we have eliminated the condition statement also, but we have to modify the body of the for loop so that the it does not become an infinite loop. This is done by using the break statement inside the for loop body. when the value of i becomes 10 , the break statement terminates the for loop. We will discuss the break statement in the next topic.

public class ForLoop
{
	public static void main(String[] args)
	{
		int i=5;
		for(;;)
		{
			Console.WriteLine("i="+i);
			i++;
			if (i==10) 
				break;
		}
		Console.WriteLine("After for loop");
	}
}
Variation 3: Infinite loop in c# using for 

The following program is an infinite loop as all the three parts of the for loop are kept empty.

public class ForLoop
{
	public static void main(String[] args)
	{
		for(;;)
		{
			Console.WriteLine("inside Infinite Loop");
		}
	}
}

foreach loop in C#

The C# foreach loop is an advanced version of C# for loop that enables to iterate over the C# collection type objects (arrays, enums, generics etc).

The programmer does not have to worry about the length of the array, the foreach loop takes care of it automatically.

Keyword in is used in the C# foreach loop syntax to get the elements stored in the specified collection.

The syntax of enhanced for loop in C#:

for (iteration_type var_name in collection)
{
	statements in body;
}

The above syntax can be read as:

for each item in collection execute the statements in the body.

Here, iteration_type specifies the data type of the elements in the collection object.

var_name is a local variable to which each of the elements of the collection is copied one by one in each iteration.

So, if there are 5 items in an array, 

  1. The first item is copied into the var_name variable  in the first iteration, 
  2. The second element is in the next iteration and so on. 
  3. In the last iteration, the 5th item is copied into the var_name variable. 
  4. After this, the for loop ends as there are no items in the array.

 

Example of foreach loop in C#:

public class ForLoop
{
	public static void main(String[] args)
	{
		int []arr={1,2,3,4,5};
		for(int item in arr)
		{
			System.Console.WriteLine("item="+item);
		}
		System.Console.WriteLine("After the for each loop");
	}
}

Output:

item=1

item=2

item=3

item=4

item=5

After the for each loop

Note: The iteration variable is just a copy of the element of the array, any change to it will not change the original array.

Advantages of for each loop in C#

  1. It eliminates the need of a loop counter variable.
  2. The start and ending conditions are not needed, foreach takes care of it automatically.
  3. There is no need to calculate the length of the array (or any collection object).
  4.  C# foreach loop has major advantage over the for loop while working with collection of web page controls and generic collections.

The above program can be written using the conventional C# for loop in this way:

public class ForLoop
{
	public static void main(String[] args)
	{
		int []arr={1,2,3,4,5};
		for(int i=0;i<arr.length; i++)
		{
			System.Console.WriteLine("item="+arr[i]);
		}
		System.Console.WriteLine("After the for each loop");
	}
}
Banner to LogicGuns.com

Hide Page Information

C#.NET Tutorial - For Loop | Example and Syntax with Explanation

This tutorial will help freshers to understand the meaning of different for loop statements in c#.net with real world example and explanation along with programs that will help beginners in c# to grasp the concept of while and do while loop in c#.net.