C# C Sharp If Else Statement

Conditional statements play a crucial role in programming by enabling developers to execute specific blocks of code based on certain conditions. Within C#, if, else if, and else statements offer programmers the flexibility to control the flow of their programs by implementing different scenarios. These programming constructs are indispensable for creating dynamic and coherent software solutions.

C# includes multiple iterations of the if statement to manage different program requirements efficiently. In C# programming, the if statement is used to test the condition. There are various types of if statements in C#.

  • if statement
  • if-else statement
  • if-else-if ladder
  • nested if statement

Each decision-making construct in C++ offers exclusive capabilities that enhance programming flexibility by executing specific functions.

C# if Statement

The C# if statement evaluates a condition and runs the code within the block if the condition is true. If the condition is false, the program exits the if block.

Syntax:

It has the following syntax:

Example

if(condition){  

//code to be executed  

}

If the condition evaluates to true, the code within the if block is executed. Conversely, if the condition evaluates to false, the code within the else block is executed.

Flow Diagram of If Statement in C#

The following CSS code snippet defines a placeholder diagram with styling for a background gradient, border radius, padding, margin, and text alignment. This diagram includes an icon and text within a centered layout.

This flowchart illustrates the implementation of an if condition within a programming context. The following is a step-by-step description of each element of the flowchart:

  1. Start Point
  • The flowchart starts with a start symbol (a small filled circle).
  • This symbolizes the beginning of the process.
  1. Condition Evaluation

The diamond symbol is used to represent a decision-making point. Here, a condition is evaluated. The decision block can result in two possible outcomes:

  • True: If the condition is True, the flow goes down.
  • False: If the condition is False, the flow skips the if block and goes straight to the next step.
  1. If Code Execution (True Condition)
  • If the condition is True, the flowchart goes to a rectangular box named "If code".
  • It indicates the execution of a collection of instructions within the if block.
  1. After If Block
  • Once the execution of the if block, control goes to the "After If" block.
  • This is the continuation of the program after passing the if statement.
  • If the condition was not True, execution directly proceeds to this block, bypassing the if code.
  1. End of Execution

The flowchart concludes with an additional small circle, denoting the conclusion of the process.

C# If Example:

Let's consider an example to demonstrate the if statement in C#.

Example

Example

using System;      

public class IfExample  

    {  

       public static void Main(string[] args)  

        {  

            int num = 10;  

            if (num % 2 == 0)  

            {  

                Console.WriteLine("It is even number");  

            }  

              

        }  

    }

Output:

Output

It is even number

Explanation:

  • Defines a class (IfExample) that serves as the program's container.
  • The program's entry point is the Main Method (Main).
  • After that, declares a variable that is an integer (num) and gives it the value 10.
  • Checks if num is Even: In order to determine whether num is divisible by 2, an if condition is used.
  • Prints Output: "It is even number" is displayed if the condition is true.
  • Expected Output: "It is even number" is printed because 10 is even.
  • C# IF-else Statement

The C# if-else statement functions by evaluating a condition and executing the if block when the condition is true; otherwise, it executes the else block.

Syntax:

It has the following syntax:

Example

if(condition){  

//code if condition is true  

}else{  

//code if condition is false  

}

Flow Diagram of the If-else Statement:

The CSS code snippet below demonstrates the styling for a placeholder diagram:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

C# If-else Example:

Let's consider a scenario to demonstrate the if-else statement in C#.

Example

Example

using System;      

public class IfExample  

    {  

        public static void Main(string[] args)  

        {  

            int num = 11;  

            if (num % 2 == 0)  

            {  

                Console.WriteLine("It is even number");  

            }  

            else  

            {  

                Console.WriteLine("It is odd number");  

            }  

              

        }  

    }

Output:

Output

It is odd number

Explanation:

  • This example, specifies a class (IfExample) that houses the logic of the program.
  • The Main Method (Main) serves as the executioner's starting point.
  • An integer variable (num) is declared, and its value is set to 11.
  • It verifies whether num is even by using an if condition to determine whether it is divisible by two.
  • It carries out if "It is even number" is printed by Block if True if the criteria is satisfied.
  • It carries out else "It is odd number" is printed by Block if False if num is not divisible by 2.
  • Expected Output: "It is an odd number" is printed because 11 is an odd number.
  • C# If-else Example: with input from user

In this instance, we are receiving user input through the Console.ReadLine function, which retrieves data as a string. To work with numerical data, it is essential to transform the input into an integer using the Convert.ToInt32 method.

Example

Example

using System;      

public class IfExample  

    {  

       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 even number");  

            }  

            else  

            {  

                Console.WriteLine("It is odd number");  

            }  

              

        }  

    }

Output:

Output

Enter a number:11

It is odd number

Output:

Output

Enter a number:12

It is even number

Explanation:

  • In this example, we defines a Class (IfExample) that contains the logic of the program.
  • The program's entry point is the Main Method (Main).
  • "Enter a number:" appears on the console when the user is prompted for input.
  • Reading User Input: This function takes a string input and uses Convert to change it to an integer.ToInt32.
  • Verifies whether the integer Is Even: An if condition is used to ascertain whether the integer is divisible by two.
  • Carries out if Prints "It is even number" if the condition is true. Block if True.
  • Carries out else Block if False: If the condition is not met, it prints "It is an odd number".
  • Dynamic Output: Using the user's input, the program decides if something is even or odd.
  • C# IF-else-if ladder Statement

The C# if-else-if ladder statement allows the execution of a single condition among several statements. This structure can manage multiple scenarios by using a sequence of if-else if conditions.

Syntax:

It has the following syntax:

Example

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  

}

Flow Diagram of the If-else-if ladder Statement:

The CSS code snippet below illustrates a placeholder diagram styled with a background gradient, border radius, padding, margin, and center alignment. The placeholder includes an icon with a font size of 3rem and text styled in a color of #9ca3af with a font size of 1rem.

C# If-else-if ladder Example:

Let's consider a scenario to demonstrate the if-else-if ladder statement in C#.

Example

Example

using System;      

public class IfExample  

    {  

        public static void Main(string[] args)  

        {  

            Console.WriteLine("Enter a number to check grade:");  

            int num = Convert.ToInt32(Console.ReadLine());  

  

            if (num <0 || num >100)  

            {  

                Console.WriteLine("wrong number");  

            }  

            else if(num >= 0 && num < 50){  

                Console.WriteLine("Fail");  

            }  

            else if (num >= 50 && num < 60)  

            {  

                Console.WriteLine("D Grade");  

            }  

            else if (num >= 60 && num < 70)  

            {  

                Console.WriteLine("C Grade");  

            }  

            else if (num >= 70 && num < 80)  

            {  

                Console.WriteLine("B Grade");  

            }  

            else if (num >= 80 && num < 90)  

            {  

                Console.WriteLine("A Grade");  

            }  

            else if (num >= 90 && num <= 100)  

            {  

                Console.WriteLine("A+ Grade");  

            }  

        }  

    }

Output:

Output

Enter a number to check grade:66

C Grade

Output:

Output

Enter a number to check grade:-2

wrong number

Explanation

  • In this example, we defines a Class (IfExample) - Encapsulates the program logic.
  • Main Method (Main): It serves as the entry point for program execution.
  • Prompts the User for Input: Displays "Enter a number to check grade:".
  • Reads and Converts User Input: Takes input as a string and converts it into an integer using Convert.ToInt32.
  • Validates Input Range: Checks if the number is outside 0-100; if true, prints "wrong number".
  • Checks Grade Conditions Using if-else Statements: Below 50 → Prints "Fail". 50-59 → Prints "D Grade". 60-69 → Prints "C Grade". 70-79 → Prints "B Grade". 80-89 → Prints "A Grade". 90-100 → Prints "A+ Grade".
  • Dynamic Output: The grade varies based on the number entered by the user.
  • Below 50 → Prints "Fail".
  • 50-59 → Prints "D Grade".
  • 60-69 → Prints "C Grade".
  • 70-79 → Prints "B Grade".
  • 80-89 → Prints "A Grade".
  • 90-100 → Prints "A+ Grade".
  • Nested-if statement:

A nested if statement in C# involves placing one if statement inside another if statement. This technique is employed when there is a requirement to evaluate multiple conditions in a sequential manner, thereby enabling more detailed decision-making processes.

Syntax:

It has the following syntax:

Example

if (condition1)

{

    // Code block for condition1

    if (condition2)

    {

        // Code block for condition2 (executed if both conditions are true)

    }

}
  • The outer if checks condition1.
  • If condition1 is true, the inner if checks condition2.
  • The inner block runs only if both conditions are true.

Example of Nested if Statement in C#

Example

Example

using System;

public class NestedIfExample

{

    public static void Main(string[] args)

    {

        int number = 25;

        if (number > 0)  // Outer if statement

        {

            Console.WriteLine("The number is positive.");

            if (number % 2 == 0)  // Inner if statement

            {

                Console.WriteLine("It is an even number.");

            }

            else

            {

                Console.WriteLine("It is an odd number.");

            }

        }

    }

}

Output:

Output

The number is positive.

It is an odd number.

Explanation:

  • Outer if checks number > 0 Since number = 25 (positive), "The number is positive." is printed.
  • Inner if checks number % 2 == 0 Since 25 is not even, the else block executes, printing "It is an odd number."
  • Since number = 25 (positive), "The number is positive." is printed.
  • Since 25 is not even, the else block executes, printing "It is an odd number."

An if-else statement in C# is a conditional statement that allows you to execute a block of code if a specified condition is true, and a different block of code if the condition is false.

The if-else statement within C# serves as a conditional control mechanism that runs varying code blocks depending on the evaluation of a specified condition as either true or false.

What is the format of an if-else statement in C#?

Example

if (condition)

{

    // Code to execute if condition is true

}

else

{

    // Code to execute if condition is false

}

Is it possible to apply multiple conditions within an if-else statement?

Yes, we have the option to utilize else if statements to evaluate multiple conditions. For instance:

Example

if (score >= 90)

{

    Console.WriteLine("Grade: A");

}

else if (score >= 75)

{

    Console.WriteLine("Grade: B");

}

else

{

    Console.WriteLine("Grade: C");

}
  1. What is the difference between if-else and switch statements in C#?
  • The if-else statement is used for conditions that involve relational and logical expressions.
  • The switch statement is preferred when checking multiple possible values of a single variable (like enums or integer comparisons).
  1. Can we nest if-else statements in C#?

Yes, it is possible to embed if-else statements inside one another. For instance:

Example

if (age >= 18)

{

    if (hasID)

    {

        Console.WriteLine("You can enter.");

    }

    else

    {

        Console.WriteLine("ID required.");

    }

}

else

{

    Console.WriteLine("You must be 18 or older.");

}

Input Required

This code uses input(). Please provide values below: