Professional Documents
Culture Documents
Control Structures
Control Structures
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
}
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:
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;
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());
}
}
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
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
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.
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;
}
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;
CS_Fig5
Analysis:
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
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;
OUTPUT
CS_Fig7
Analysis
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.
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 .
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
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[].