Course C# Programming Basics for Beginners
.Net C# CSharp

Control flow statements

( 12 users )

Like in any programming language, C# provides statements that can change the sequence of program execution. If you have seen or worked with flow charts, you can easily visualize that it's very frequent when we require decision boxes that indicate how the program flow can change based on condition(s). So, let's see how we can use different C# statements to control and change the flow of program execution.

The "if" statement

The "if" statement provides a block of code which can be executed only when the specified condition in an "if" statement evaluates to true. Let's see this with the help of an example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The if statement");
		Console.WriteLine("");
		
		int width = 20;
		int length = 20;
		
		if(width == length)
		{
			Console.WriteLine("A square is detected");
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

// Output : A square is detected.
		

In the above example, the line "A square is detected" gets printed when the condition "width == height" is true. This also means we have changed the program flow based on a condition.

The "if-else" statement

Just like "if-else" statement adds an "otherwise" condition in the program flow. The additional "else" block will be executed only when the condition mentioned with "if" statement turns out to be false. Let's modify the above example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The if-else statement");
		Console.WriteLine("");
		
		int width = 20;
		int length = 25;
		
		if(width == length)
		{
			Console.WriteLine("A square is detected");
		}
		else
		{
			Console.WriteLine("A rectangle is detected");
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

// Output : A rectangle is detected
		

In the above example, the line "A rectangle is detected" gets printed when the condition "width == height" is false.

The "if-elseif-else" statement

In the previous statements, we were changing the program flow based on one condition only. So, what if we want to control the program flow based on multiple condition. The "if-elseif-else" statement gives us such kind of provision. Let's see this with the help of an example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The if-else-if statement");
		Console.WriteLine("");
		
		int alice_age = 20;
		int bob_age = 15;
		
		if(alice_age < bob_age)
		{
			Console.WriteLine("Alice is younger than Bob");
		}
		else if(alice_age > bob_age)
		{
			Console.WriteLine("Alice is elder than Bob");
		}
		else
		{
			Console.WriteLine("Both Alice and Bob are equal in age");
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

// Output : Alice is elder than Bob
		

In the above example, we have multiple conditions and whichever condition satisfies, the program flow will follow that path. We can add multiple conditions by specifying multiple "else if" clauses.

The "switch" statement

When we want to control the program flow based on the value of one variable or expression only, then the "switch" statement gives us a very clean way of doing it. So instead of using "if-else", we can use a "switch" statement and write program statements against each value. state to make the code more readable. Let's see this with the help of an example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The switch statement");
		Console.WriteLine("");
		
		int direction = 3;
		
		switch(direction)
		{
			case 1:
				Console.WriteLine("Moving north");
				break;
			case 2:
				Console.WriteLine("Moving east");
				break;
			case 3:
				Console.WriteLine("Moving south");
				break;
			case 4:
				Console.WriteLine("Moving west");
				break;
			default:
				Console.WriteLine("Invalid direction");
				break;
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

// Output : Moving south
		

Let's understand the above program. We have provided the variable "direction" to the "switch" construct. Now, as the value of "direction" is "3", the switch statement will make a jump to case 3 and execute the block of statement(s) under it which in this case will print "Moving south".

The break; statement is optional but necessary. If there is no break; statement, the program flow will continue to the next case and will execute that as well.

The "default" case is executed when there is no other matching case in the "switch" statement. In the above example, if the value of direction is 6, then the default case will execute and print "Invalid Direction".

Note : In terms of performance, switch statement is better to use because unlike if-else, the condition is evaluated only once and based on the value the switch statement makes a direct jump to the corresponding programming block.

The "for" loop

The "for" loop allows us to repeat some block of statement(s) for a particular number of times. In general the format of a "for" statement in C# is as follows.


for(initialization; condition; iteration steps)
{
	statement(s);
}
		

In "initialization", we initialize a variable that is used to control the number of times the block under for statement would be executed. The condition is a boolean expression which specifies that the block under "for" statement will get repeated until the condition is true. The "condition" expression when true terminates the iteration. The last section "iteration steps" uses to change the "control variable" (the variable that we initialize in "initialization") so that it reaches near to the "condition" on every iteration.

If you are still not clear, let's understand this with an example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The for loop statement");
		Console.WriteLine("");
		
		for(int i=0; i < 5; i++)
		{
			Console.WriteLine(i);
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

/* 

Output : 

0
1
2
3
4

*/
		

Here, in the above example, we have initialized a control variable "i = 0". The statement Console.WriteLine(i); will be repeated till the condition "i < 5" is true. The i++ is making sure that on every iteration we are getting closer to the condition when "i < 5" becomes false and the loop terminates. Every-time before exiting the loop, the i++ gets executed i.e. increments the value of i.

The "while" loop

There is another kind of looping statement called "while" loop. In general the format of the "while" loop is as follows.


while(condition)
{
	statement(s);
}
		

The block of statement(s) under while loop would be executed till the condition expression is true. So its the responsibility of a developer to control the condition expression within the statement body of the while loop. Let's see this in the below example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The while loop");
		Console.WriteLine("");
		
		int i=0;
		while(i < 5)
		{
			Console.WriteLine(i);
			i++;
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

/* 

Output : 

0
1
2
3
4

*/
		

If you notice that it is similar to the for loop. A variable (i) is initialized before while loop. The condition "i < 5" is specified with while loop. The line "Console.WriteLine(i);" is written within the statement body of while loop and the control variable "i" is getting incremented at the end of statement body of the while loop. Hence, every for loop can be converted into while loop and vice versa.

The "do-while" loop

It is another looping construct. The syntax of a do-while loop is as follows.


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

Now, if you notice here, there is a slight format change in "do-while" loop as compared to the "while" loop. The condition is specified at the end. This means that even if the condition is false before loop execution, this loop is guaranteed to execute at least once.

So, let's use the same example and write in "do-while" format:

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The do-while loop");
		Console.WriteLine("");
		
		int i =0;
		do
		{
			Console.WriteLine(i);
			i++;
		}
		while(i < 5);
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

/* 

Output : 

0
1
2
3
4

*/
		

The "foreach" loop

The "foreach" loop is a very concise way to iterate over collections like arrays, lists etc. These collections will be covered later in this course and then we'll discuss more on foreach loop then.

The "break" and "continue" statements

The "break" statement is used to prematurely exit from a loop. Let's see the below example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The break statement");
		Console.WriteLine("");
		
		for(int i=1; i < 10; i++)
		{
			if(i % 7 == 0)
			{
				break;
			}
			Console.WriteLine(i);
		}
		
		Console.WriteLine("");
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

/* 

Output : 

1
2
3
4
5
6

*/
	

In the above program, we are breaking the loop when then condition "i % 7 == 0" is true. If you see the output of this code, only 1 to 6 numbers are getting printed.

In contrast, the"continue" statement have some different behaviour. As soon as, the block of any looping construct encounters the continue statement, instead of executing the next statement, it continues the loop for the next iteration. Let's modify the precious example and replace the break statement with continue.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("The continue statement");
		Console.WriteLine("");
		
		for(int i=1; i < 10; i++)
		{
			if(i % 7 == 0)
			{
				continue;
			}
			Console.WriteLine(i);
		}
		
		Console.WriteLine("");
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}

/*
Output : 

1
2
3
4
5
6
8
9

*/
	

In the above example, when the condition "i % 7 == 0" is true, the loop won't execute further lines in the block of statements under that loop and so it wont print the value of "i" at that iteration. Hence, 7 will not be printed to the screen. If you see the output of this program, you will find that 7 was not printed but the loop continued for the rest of the iteration.

To Do

* Note : These actions will be locked once done and hence can not be reverted.

1. Track your progress [Earn 200 points]

2. Provide your ratings to this chapter [Earn 100 points]

0
Operators in C#
Arrays in C#