C# If Statement

C# If Statement: The Control Structures help us to control the flow of the application code execution. These flow control structures are categorized into two types—they are Branching and looping.

Control Flow Chart

Branching is useful for decision-making by selecting one option from multiple options. In case we want to decide on multiple options, we opt for C# 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.

Simple C# If Statement

The simple if statement in C# is useful to execute code only if the condition specified in the if statement is true. The syntax of the if statement is as shown below

If<condition>
{
   Statements; //These statements are executed if condition is true
}

C# If Statement Example

In this C# if statement example, we write code for the following requirement.

Read numbers 1 to 4 and print in words. If the number is not between 1 to 4, then print it as invalid.

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

C# If Statement Example 1

ANALYSIS

Using the C# if statements in the above code, 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 a string, and we explicitly convert it to an integer using Parse.int

The input number is given as 3

The C# compiler started checking number 3 with 1, 2, 3,4, and hence it is 3. It has given output as follows.

the input number is three

NOTE: The compiler checks every if condition in the code, and it won’t exist even after the condition is satisfied in the middle of the code itself, i.e., i==3 in the above example code.

Categories C#