C# Control Statements
C# Control Statements
Control statements
• if statement
• if-else statement
• nested if statement
• if-else-if ladder
• Switch
• For
• While
• Do while
• Break
• Continue
• goto
If statement
The syntax is,
if(condition)
{
//code to be executed
}
Example:
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 7;
if (num % 2 != 0)
{
Console.WriteLine("It is an odd number");
}
}
}
If – else statement
The syntax is,
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
using System;
public class IfelseExample
{
public static void Main(string[] args)
{
int num = 7;
if (num % 2 != 0)
{
Console.WriteLine("It is an odd number");
}
else
{
Console.WriteLine("It is an even number");
}
}
}
If-else-if Ladder Statement
The syntax is,
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
using System;
namespace dotnet_sample
{ class Program
{ static void Main(string[] args)
{ int first=10, second=20, third=15;
if (first > second)
{ if (first > third)
{ Console.WriteLine("Largest number: " + first);
}
else
{ Console.WriteLine("Largest number: " + third);
}
}
else { if (second > third)
{ Console.WriteLine("Largest number: " + second);
}
else
{ Console.WriteLine("Largest number: " + third);
}
} } }
}
Example - To get input from user
• Console.ReadLine() method. It returns string.
• For numeric value, you need to convert it into int
using Convert.ToInt32() method or int.Parse() method
Numeric type Method
decimal ToDecimal(String)
float ToSingle(String)
double ToDouble(String)
short ToInt16(String)
int ToInt32(String)
long ToInt64(String)
ushort ToUInt16(String)
uint ToUInt32(String)
ulong ToUInt64(String)
Example:
using System;
public class IfelseExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());
if (num % 2 == 0)
{
Console.WriteLine("It is an odd number");
}
else
{
Console.WriteLine("It is an even number");
}
}
Switch statement
The syntax is,
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
break;
}
For loop
The syntax is,
for(initialization; condition; incr/decr){
//code to be executed
}
While loop
The syntax is,
while(condition){
//code to be executed
}
Do – while loop
The syntax is,
do{
//code to be executed
}while(condition);
using System;