Conditional Constructs

Conditional constructs are used to control the flow of program . conditional constructs allow the flow selective execution of statements , depending on the value of the expressions associated with them. The comparison operators are required for evaluating the conditions . various conditional constructs are :

1. if....else construct.
2. switch... case construct.

  • if....else construct
    if...else conditional construct is followed by a logical expression where data is compared and a decision is made on the basis of the result of the comparison. syntax is
if (expression)
{
statements;
}
else
{
statements;
}
example:

class Number
{
static void Main(string [] arg)
{
int num;

Console.WriteLine("Enter the number: \t");
num=Convert.ToInt32(Console.ReadLine());

if(num%!=0)
{
Console.WriteLine(" Number is odd");
}
else
{
Console.WriteLine(" Number is even");
}


if....else constructs can be nested inside each other. This process of using multiple if....else constructs is known as cascading if ...else. consider the example :
int n1=5;
int n2=6;
int n3=7;
if(n1>n2)
if(n1>n3)
{
Console.WriteLine("Number 1 is great");
}
else
{
Console.WriteLine("number 3 is great");
}
else if(n2>n3)
{
Console.WriteLine("number 2 is great");
}
else
{
Console.WriteLine("number 3 is great");
}
  • switch...case construct
This construct is used when there are multiple values for a single variable. syntax for this construct is
switch(variable name)
{
case option: statement;
break;
case option: statement;
break;
default: statement;
}

0 Comments:

Post a Comment



Newer Post Older Post Home