05 Feb 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:
1 2 3 4 5 |
if(condition) { // statements execute if the condition is true } |
Let us see an example of the if statement in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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
1 2 3 |
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:
1 2 3 4 5 6 7 8 |
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#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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
1 2 3 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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
1 2 3 |
The value is more than 5 |
No Comments