Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Control Structures in C#

Control Structures help us to control the flow of the application code execution.
These flow control structures categorized into two types.
Branching and looping.

CS_Fig

Branching
Branching is used for making decision by selecting one option from multiple options.
In case if we want to take decision on multiple options, we opt for branching statements
like if, if else etc.

For example if we want to check whether a number is odd or even, then we have to
decide based on two options i.e., whether that number is divisible by two or not.

CS_Fig0

SIMPLE IF Statement:
Simple if is used to execute code, only if the condition specified in the if is true

Syntax:

If<condition>
{
Statements; //These statements are executed if condition is true
}

For example let us write code for the following requirement

Read numbers 1 to 4 and print in words, if the number is not in between 1 to 4 then print
as invalid number.

using System;
class Program
{
static void Main()
{
int i = int.Parse(Console.ReadLine());

if (i == 1)
{
Console.WriteLine("input number is one");
}
if (i == 2)
{
Console.WriteLine("input number is two");
}
if (i == 3)
{
Console.WriteLine("input number is three");
}
if (i == 4)
{
Console.WriteLine("input number is four");
}
if (i != 1 && I != 2 && I != 3 && I != 4)
{
Console.WriteLine("input number is invalid");
}
}
}

OUTPUT

CS_Fig1

Analysis

In the above code, using if statements we compared the input number with the
numbers 1 to 4.
Here we have taken an integer variable i to store the input number
Since Console.ReadLine() returns string, we explicitly converted to integer using
Parse.int
The input number is given 3
The compiler started checking number 3 with 1, 2, 3,4, and hence it is 3, it has given
output as follows
Input number is 3
Note:
The compiler checks each and every if condition in the code, and it wont exit even after
the condition is satisfied in the middle of the code itself i.e., i==3 in the above example
code.

If Else Statement:
if else control statement is having two blocks. One is true block another one if false
block.
In case condition in if is true, the statements in if block are executed, if it is false, the
statements in the else block are executed.

Syntax:

if <condition>
{
Statements //These statements are executed if condition is true
}
else
{
Statements //These statements are executed if condition is false
}

Let us see an example on if else by finding whether the given input number is even or
odd?…

using System;
class Program
{
static void Main()
{
int i = int.Parse(Console.ReadLine());

if (i % 2 == 0)
{
Console.WriteLine("{0} is even number", i);
}
else
{
Console.WriteLine("{0} is odd number", i);
}
}
}

OUTPUT
CS_Fig2

Analysis:

In the above code we have taken integer variable i


Since Console.ReadLine() returns string, we explicitly converted to integer using
Parse.int
Input number is given 7
Since 7%2 =1 the output is
7 is odd number

Else if Ladder
Using Else if statements we can increase the speed of execution over simple if
statements. That means when we use Else if control flow statements, the compiler will
check all the comparisons in the sequence only until the given condition is satisfied.
Once the condition is satisfied, rather than going for the next comparison, it will exit
there itself.
Else if control statements will overcome the performance issues with the simple if
statements

Syntax:

if <condition>
{
Statements //These statements are executed if condition is true
}
else if <condition>
{
Statements //These statements are executed when this else if condition is true
}
else if <condition>
{
Statements //These statements are executed when this else if condition is true
}
else
<Default statements> //These statements are executed in case when neither of the
above conditions is true.

Let us write the code using else if, for the example seen in if control statements

Read numbers 1 to 4 and print in words, if the number is not in between 1 to 4 then print
as invalid number.

using System;
class Program
{
static void Main()
{
int i = int.Parse(Console.ReadLine());

if (i == 1)
{
Console.WriteLine("input number is one");
}
else if (i == 2)
{
Console.WriteLine("input number is two");
}
else if (i == 3)
{
Console.WriteLine("input number is three");
}
else if (i == 4)
{
Console.WriteLine("input number is four");
}
else
{
Console.WriteLine("input number is invalid");
}
}
}

OUTPUT
CS_Fig3

Analysis:
Here i = 2 is given as input.
First it checks for 2==1 which is false
2==2 returns true
Hence it prints
Input number is 2
And it quit from the loop without executing the next statements.

Nested if statements
Using Nested if statements, we can write number of if or else if conditions inside one if
or else if condition.

In the real time, we can come across scenarios where we have to make one decision by
checking multiple conditions
Syntax:
If <condition>
{

If <condition>
{
Statements;
}
else if<condition>
{
Statements;
}
else
Default statements
}
else
Default statements;

For example, Let us assume that for a particular job requirement

Job profile is as follows:


Candidate should be from it or csc department
Academic percentage >=60
Age <50

If all the above conditions are satisfied, then the person is eligible for the post
Let us write C# code for the above scenario

using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter your Department");
string Department = (Console.ReadLine());

if (Department.ToUpper() == "IT" || Department.ToUpper() == "CSC")


{
Console.WriteLine("Enter your Percentage");
int Percentage = int.Parse(Console.ReadLine());

if (Percentage >= 60)


{
Console.WriteLine("Enter your age");
int Age = int.Parse(Console.ReadLine());
if (Age < 50)
{
Console.WriteLine("You are eligible for this post");
}
else
Console.WriteLine("Your age is not suitable for the requirement");
}
else
Console.WriteLine("Your Percentage is not suitable for the requirement");
}
else
Console.WriteLine("Your qualification is not suitable for the requirement");

}
}

OUTPUT
CS_Fig4

ANALYSIS
Here we have given Department name as ‘csc’
Since it satisfies the condition, it entered into inner if
And asks for the Percentage
Percentage given as 40
Since this percentage condition is failed because percentage should be >= 60 to enter
into inner if i.e., age condition
The compiler exit from the loop and print the else part i.e.,
Your percentage is not suitable for the requirement.

LOOPING

Looping is a mechanism in which some instructions are repeatedly executed until


certain condition is reached.
C# supports looping mechanisms like while, do while, for loop, for each loop
For loop is a Range based loops
while loop and do while loop are condition based loops.

If we know the range of how many times the loop should be executed, then we use for
loop.
In case if we don’t know the range, we use while loop and do while loop

For example, if we want to print odd numbers from 1 to 10,


In this case we know that the loop should be executed 10 times, so we go with for loop.

But there will be a case where we have to fetch particular data from the database,
In that case we don’t know how many records are available in the database, so we have
to use while or do while loop to iterate the loop until the data is fetched.

Every loop will have three sections


1. Initialization (It is nothing but assigning a value to a variable)
Syntax:
<Datatype> <variablename> = value;
Ex:
int i =10;

2. Condition (Condition is to compare two or more values or expressions and it will


return Boolean value.)
Ex:
5 <= 7-2; which returns true

3. Increment/Decrement ( incrementing or decrementing a variable value)


Ex:
Int i = 5;
i++; it will increment i by 1
i=i-2; it will decrement i by 2

While loop

While loop is a condition based loop and it will check the condition before executing the
block of code.

Syntax:
while(<Boolean expression>)
{
Statements;
}

Here the expression returns a boolean value.


When the expression returns true, the control enters into the block and the statements
in it are executed.
Once the statements in the block get executed, the control again returns to the
condition.
This process gets continued until the condition returns false. Once the Boolean
expression returns false, the control skips the block of code in the while loop and starts
executing the statements after the closing brace.

While writing statements inside the block, we should make sure to update variables
associated with the expression so that the loop gets ended when we want to, to avoid
keeping on iterating inside the loop infinitely.

Let us demonstrate the code using while loop to print I value from 2 to 10 until the
condition i<=10 is satisfied by incrementing I with 3

using System;

public class Program


{
static void Main()
{
int i = 2;
while (i <= 10)
{
Console.WriteLine(i);
i+=3;
}
Console.WriteLine("Control is out of loop");
Console.ReadLine();
}
}
OUTPUT:

CS_Fig5

Analysis:

Here i is initialized with 2


Boolean expression i<=10 i.e., 2<=10 which returns true
So control enters into block and executes the statements
i.e., 2 is printed
And then i is incremented by 3
So i = 2+3 = 5

Again condition checking, 5<=10 returns true


So 5 is printed
i = 5+3 = 8

Again 8<=10 returns true


So 8 is printed
i= 8+3=11

Again 11<=10 returns false


Control comes out of loop and executes the statements after closed brace
i.e., Control is out of loop

Do While Loop

Do while loop is quite similar to the while loop except one thing.
In do while loop, the statements inside the loop are executed once and then it checks
the condition. So do while guarantees to execute the statements of the loop at least
once.

Syntax:
do
{
statements;
}while<boolean expression>
Let us see an example code using do while loop to read value of integer n from user and
print integers until n<=5 returns true

using System;

class program
{
public static void Main()
{
Console.Write("Enter an integer {0}", " ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine();
do
{
Console.WriteLine(n);
n++;
} while (n <= 5);
Console.ReadLine();
}
}

OUTPUT
CS_Fig6

Analysis

First output: input is 2

Here control asks the user to enter some integer


Input is given 2
Now it prints the integer 2
2++ which is 3
It will check the condition 2<=5, which returns true
Again the loop repeats
By printing the n value i.e., 3
3++ which is 4
It will check the condition 3<=5, which returns true
..
Until n value is 5, the loop will be repeated
When n = 5, control prints the value 5 an d then increments
5++ = 6
Now the condition 6<=5 returns false
So the control comes out of the loop.
Second output: input is 6

Here in this case as usual control reads the input 6 and enters the do loop
Where it prints the value 6 and increments
i.e., 6++ = 7
Now it checks for the condition 7<=5 which returns false
So it quits the loop by printing 6 as output

For Loop

For loop is a range based loop i.e., we can use for loop when we know particularly how
many times the loop has to be repeated
All the three sections initialization, condition check and the increment/decrement will
be in the same line in for loop with comma separation.

Syntax:
For(<initialization>; <boolean expression>; <increment/decrement>)
{
Statements;
}

A part from the syntax the working of for loop is same as the while loop.
i.e.,
Once the variable is get initialized, it will check for the boolean expression and if
boolean expression evaluates to true, it enters the loop and executes the statements
inside the loop and next Increment/decrement of that variable is done. Again checks for
the condition.
This process is repeated until the boolean expression evaluates to true. Once it returns
false, control comes out of the loop and continues the execution of the statements after
the closing brace of the loop.

Let us see an example code using for loop to print even numbers from 0 to 10

using System;

class program
{
public static void Main()
{
for (int i = 0; i <= 10; i++)
{
if (i == 10)
break;

if (i % 2 != 0)
continue;

Console.Write("{0} ", i);


}
Console.ReadLine();
}
}

OUTPUT

CS_Fig7

Analysis

Here i is an integer variable initialized with 0


Control enters the loop and checks if i==10 which returns false
It checks 0 % 2 !=0 is false, hence continue is not executed and prints 0

i is incremented i.e., i=1


Control enters the loop and checks if i==10 which returns false
It checks 1 % 2 !=0 is true, hence continue is executed and skips the print statement

i is incremented i.e., i=2


Control enters the loop and checks if i==10 which returns false
It checks 2 % 2 !=0 is false, hence continue is not executed and prints 2
.
.
When I is incremented to 10
Control enters the loop and checks if i==10 which returns true
So break statement is executed and control comes out of the loop.

For each Loop

For each loop is used to iterate through each item in a collection. Generally this loop is
used with ArrayList, Generics etc.
Syntax:
foreach(<datatype> <variable> in <list>)
{
statements;
}
Here the <datatype> is nothing but the type of the item present in the list. In case the
type of the list is for example int[], then here the <datatype> will be int.

The variable can be any one but the one which is meaningful is suggested.

In is a keyword which is mandatory.

The list is an array or even a collection.

Here the variable used in the foreach syntax is a read only variable which will read the
value from the list as long the list returns the value .

Let us see an example code using foreach loop


We are writing code by defining one integer array holding four values in it. By using
foreach loop we are going to print all the items in the integer array list.

using System;

class program
{
public static void Main()
{
int[] array= { 1, 2, 3, 4 };
Console.WriteLine("Items in the array are");
foreach (int i in array)
{
Console.Write("{0} ", i);
}
Console.ReadLine();
}
}

OUTPUT

CS_Fig8

Analysis

array is an integer array which is holding four values 1, 2, 3, 4

As shown in the syntax, we just taken a variable i of type integer to read values or items
from the list array[].

i reads one item from the list at a time and the foreach loop is repeated until the last
item in the list is returned.
Here we are printing all values which the variable I is reading from the list array[].

You might also like