If Else C#

If Statement

One of the most important control flow statements in every programming language is the if statement. In the if statement, a condition or a set of conditions is checked. If the condition is fulfilled, the program control enters into the if block and executes all the statements as well as instructions defined inside the if block. The syntax of the if statement is as follows:

int Number1, Number2;
if(Number1>Number2) // condition
{
  Console.WriteLine("Number1 is greater than Number2"); // statement
}

In the preceding code snippet, if the condition stated in the if statement is true, then the message, Number1 is greater than Number2, is displayed.

If-Else Statement

However, sometimes the condition inside the if statement is not fulfilled. In such cases, C# provides the if-else statements that execute a block of code when a certain condition is fulfilled and another block of code when a certain condition is not fulfilled. The following code snippet shows the use of the if-else statement.

if(Number1>Number2) // condition 
{
  Console.WriteLine("Number1 is greater than Number2"); // statement
... //statements 
}
else
{
  Console.WriteLine("Number2 is greater than Number1"); // statement
... //statements
}

In the preceding code snippet, when the condition (Number1>Number2) is not fulfilled, the program control transfers to the else block and executes the block of code inside it.

Nested If-Else Statement

To evaluate multiple conditions one by one, you can do nesting of if-else statements. The following code snippet shows an example to understand the syntax of the nested if-else statement:

if(Number1 > Number2 && Number1 > Number3 ) // condition 
{
Console.WriteLine("Number1 is the greatest"); // statement
... //statements
}
else
{
if(Number2 > Number3) //condition
{
Console.WriteLine("Number2 is greatest"); // statement
... //statements
}
else
{
Console.WriteLine("Number3 is greatest"); // statement
... //statements
}
}

In the preceding code snippet, first a condition (Number1 > Number2 && Number1 > Number3) is checked in the if block. If it is fulfilled, the statement inside the if block is executed; otherwise, the program control transfers to the else if block and checks another condition (Number2 > Number3). If this condition (Number2 > Number3) is fulfilled, then the statement inside the else if block gets executed; otherwise, the program control transfers to the else block.



Write a comment


Name Email Message