C# Decision Making Statements

In Decision making, one or more conditions are evaluated by the program. The following are the decision-making statements in C#:

  • if
  • if…else
  • if…elseif..else

The if statement in C#

Under if, the statement executes if the condition is true. The syntax is as follows:

if(condition) {
   // statements execute if the condition is true
}

Let us see an example of the if statement in C#:

using System;

namespace Demo
{
  class Studyopedia
  {
    static void Main(string[] args)
    {         
      int i = 10;
    
      // if statement
      if(i>5)
        Console.WriteLine("The value is more than 5");
     }
  }
}

Output

The value is more than 5

The if…else statement in C#

Under if-else statement, the first statement executes if the condition is true, else statement 2 executes.

The syntax is as follows:

if(condition) {
   // statement1 execute if the condition is true
}
else {
  // statement2 execute if the condition is false
}

Let us see an example of the if…else statement in C#:

using System;

namespace Demo
{
  class Studyopedia
  {
    static void Main(string[] args)
    {         
      int i = 5;
    
      // if statement
      if(i>5) {
        Console.WriteLine("The value is more than 5");
      } else { // else statement
        Console.WriteLine("The value is less than or equal to 5");
      }
     }
  }
}

Output

The value is less than or equal to 5

The if…elseif…else statement in C#

The if-else if-else executes and whichever condition is true, the associated statement executes. If none of them is true, then else executes.

The syntax is as follows:

if(condition) {
   // statement executes when this condition is true
} else if(expression) {
   // statement executes when this condition is true
} else if(condition) {
      // statement executes when this condition is true
} else if(condition) {
      // statement executes when this condition is true
} else {
   // this statement executes when none of the condition is true.
}

Let us see an example of the if…elseif…else statement in C#:

using System;

namespace Demo
{
  class Studyopedia
  {
    static void Main(string[] args)
    {         
      int i = 25;
    
      // if statement
      if(i > 5) {
        Console.WriteLine("The value is more than 5");
      } else if(i > 50){ // else if statement
        Console.WriteLine("The value is more than 10");
      } else { // else statement
        Console.WriteLine("The value is less than or equal to 5");
      }
     }
  }
}

Output

The value is more than 5
C# - Loops
C# Data Types
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment