Contents
Introduction
C# Uses control structures are like flow controller based on the condition it controls the flow of a program. In other words, a control structure determines the order in which the program is executed. Control structure can be put in the following categories:
- Conditional structures – Conditional structures allow the program to choose different paths of execution based upon the outcome of an expression
- Iteration structures – Iteration structures allow program execution to repeat one or more statements
- Jump statements – Jump statements allow the program to execute in a nonlinear fashion.
- Exception handling – handle exchange gracefully so the program will execute gracefully.
Conditional structures
C# supports two Conditional structures i.e. if and switch. These Conditional structures allow controlling the flow of program based on a run time condition.
if statement
Use the if statement to specify a block of C# code to be executed if a condition is True.
if(boolean condition)
{
// code to execute if the boolean condition is true
}
If condition meets, then only code if if block will get execute
using System;
namespace Applications
{
class Program
{
static void Main()
{
Console.WriteLine("What is 2 + 2");
int x = Convert.ToInt32(Console.ReadLine());
if (x == 4)
{
Console.WriteLine("Correct!");
}
else
{
Console.WriteLine("Wrong!");
}
Console.ReadKey();
}
}
}
In the above program if you enter the value to 4 then only it will display “Correct!” message otherwise program will print the message as “Wrong!”.
We can add multiple if condition block or nested block in our program below is the syntax for the same.
if(boolean condition)
{
// code to execute if the boolean condition is true
if(boolean condition)
{
// code to execute if the boolean condition is true
}
}
else if(boolean condition)
{
// code to execute if the boolean condition is true
}
else if(boolean condition)
{
// code to execute if the boolean condition is true
}
else
{
// code to execute if the boolean condition is true
}
Switch Statement
The switch statement works as a filter for different values. each value of expression considers as a “case”. To break the flow of case the keyword break is typically used to end a case. An unconditional return in a case section can also be used to end a case.
Syntax
switch(expression)
{
case expression1 :
// code to execute
break;
case expression2 :
// code to execute
break;
case expression3 :
// code to execute
break;
default :
// code to execute
}
Code example
using System;
namespace Applications
{
class Program
{
static void Main(string[] args)
{
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Good!");
break;
case 'C':
Console.WriteLine("Need to work hard!");
break;
case 'D':
Console.WriteLine("Fail!");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}
Iteration structures
C# Iteration structures are for, while, foreach, do-while. these Iteration structures use to create a loop to repeat one or more statements until the expression is true.
While Loop
While loop is the most fundamental loop in programming, it repeats the block of code while its controlling expression is true.
Syntax
while(condition)
{
// code to execute
}
Code
using System;
namespace Applications
{
class Program
{
static void Main(string[] args)
{
int a = 10;
while (a > 0)
{
Console.WriteLine($"Tick: {a}");
a--;
}
Console.ReadLine();
}
}
}
Program of above code
Tick: 10
Tick: 9
Tick: 8
Tick: 7
Tick: 6
Tick: 5
Tick: 4
Tick: 3
Tick: 2
Tick: 1
Do-While
In a while loop, we saw that if conditional expression initially is false then while loop never executes the body of the loop. However, sometimes it is desirable to execute the body of the loops at least once even if the condition expression is false, in other words when we want to test the termination expression at the end of the loop rather than beginning we need to use a do-while loop.
Syntax
do
{
// code to execute
} while( condition expression );
Code
using System;
namespace Applications
{
class Program
{
static void Main(string[] args)
{
int a = 10;
do
{
Console.WriteLine($"Tick: {a}");
a--;
} while (a > 0);
Console.ReadLine();
}
}
}
Output of the program:
Tick: 10
Tick: 9
Tick: 8
Tick: 7
Tick: 6
Tick: 5
Tick: 4
Tick: 3
Tick: 2
Tick: 1
For loop
The for loop consists of three parts: declaration, condition, and counter expression.
So when the loop starts the declaration portion of the loop get executed. Generally, this is an expression that sets the value of loop control variables; the next is condition this must be a Boolean expression. It usually tests the loop control variable against the target value, if the value is true then the only loop will get execute else loop will get terminates; the last part is a counter expression that increment or decrement the loop control variables.
Syntax
for (int i = 0; i < 10; i++)
{
// code to execute
}
Code
using System;
namespace Applications
{
class Program
{
static void Main(string[] args)
{
for (int a = 10; a > 0; a--)
{
Console.WriteLine($"Tick: {a}");
}
Console.ReadLine();
}
}
}
Output of above code
Tick: 10
Tick: 9
Tick: 8
Tick: 7
Tick: 6
Tick: 5
Tick: 4
Tick: 3
Tick: 2
Tick: 1
foreach loop
The foreach statement is derived from the for statement and makes use of a certain pattern described in C#’s language specification in order to obtain and use an enumerator of elements to iterate over.
Each item in the given collection will be returned and reachable in the context of the code block. When the block has been executed the next item will be returned until there are no items remaining.
Syntax
foreach (int i in iList)
{
// code to execute
}
Jump statements
C# Supports three jump statements goto, break, continue, return Jump statements allow program to execute in nonlinear fashion.
Goto
Goto is used to transfer control to the labelled statement in the program. So Labels are given points in code that can be jumped to by using the goto statement.
Syntax
start:
//line of codes
goto start;
Code
using System;
namespace Applications
{
class Program
{
static void Main(string[] args)
{
start:
Console.WriteLine("What is 2+2");
int x = Convert.ToInt32(Console.ReadLine());
if (x != 4)
{
goto start;
}
Console.WriteLine("Correct");
Console.ReadLine();
}
}
}
break
The break statement is used to terminate the loop or switch statement. After break, the control will pass to the statements that present after the break statement, if available.
Syntax
int e = 10;
for (int i = 0; i < e; i++)
{
while (true)
{
break;
}
// Will break to this point.
}
Code
using System;
namespace Applications
{
class Program
{
static void Main(string[] args)
{
int x;
do
{
Console.WriteLine("What is 2+2");
x = Convert.ToInt32(Console.ReadLine());
if (x == 4)
break;
} while (x != 4);
Console.WriteLine("Correct");
Console.ReadLine();
}
}
}
Continue
The continue statement discontinues the current iteration of the current control statement and begins the next iteration.
Syntax
int ch;
for (int i = 1; i <= 10; i++)
{
if (i == 4)
continue; // Skips the rest of the while-loop
// rest code for execution
}
Code
using System;
namespace Applications
{
class Program
{
static void Main()
{
for (int i = 0; i <= 10; i++)
{
if (i == 5)
continue;
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Return
This statement terminates the execution of the method and returns the control to the calling method.
Syntax
switch(condition)
{
case 1:
return "one";
case 2:
return "two";
default:
return "invalid";
}
Code
using System;
namespace Applications
{
class Program
{
static void Main()
{
bool condition = true;
Console.WriteLine("Print");
if (condition)
return;
Console.WriteLine("This will not Print");
}
}
}
Exception handling
Exception handling is required to handle the exception grass fully at run time.
Syntax
try
{
// Statements which may throw exceptions
...
}
catch (Exception ex)
{
// Exception caught and handled here
...
}
finally
{
// Statements always executed after the try/catch blocks
}
The statements within the try block are executed if any of the code line throws an exception, execution of the block is discontinued, and the exception is handled by the catch block and control will be passed to the catch block. There may be multiple catch blocks, in which case the first block with an exception variable whose type matches the type of the thrown exception is executed. At least finally block is always executed after the try and catch blocks, whether or not an exception was thrown. finally, blocks are useful for providing clean-up code.
Code
using System;
namespace Applications
{
class Program
{
static void Main()
{
try
{
Console.WriteLine("What is 2 + 2");
int x = Convert.ToInt32(Console.ReadLine());
if (x == 4)
{
Console.WriteLine("Correct!");
}
else
{
Console.WriteLine("wrong!");
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.ReadLine();
}
}
}
}
For more information you can read exception handling