Algorithm


In C#, conditional statements like if, if...else, if...else if, and nested if statements are used to control the flow of execution based on certain conditions. Here's a brief overview of each:

Code Examples

#1 C# Programming if (if-then) Statement

Code - C# Programming

using System;

namespace Conditional
{
	class IfStatement
	{
		public static void Main(string[] args)
		{
			int number = 2;
			if (number  <  5)
			{
				Console.WriteLine("{0} is less than 5", number);
			}

			Console.WriteLine("This statement is always executed.");
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
2 is less than 5
This statement is always executed.

#2 C# Programming if...else Statement

Code - C# Programming

using System;

namespace Conditional
{
	class IfElseStatement
	{
		public static void Main(string[] args)
		{
			int number = 12;

			if (number  <  5)
			{
				Console.WriteLine("{0} is less than 5", number);
			}
			else
			{
				Console.WriteLine("{0} is greater than or equal to 5", number);
			}

			Console.WriteLine("This statement is always executed.");
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
12 is greater than or equal to 5
This statement is always executed.

#3 C# Programming if...else if Statement

Code - C# Programming

using System;

namespace Conditional
{
	class IfElseIfStatement
	{
		public static void Main(string[] args)
		{
			int number = 12;

			if (number  <  5)
			{
				Console.WriteLine("{0} is less than 5", number);
			}
			else if (number > 5)
			{
				Console.WriteLine("{0} is greater than 5", number);
			}
			else
			{
				Console.WriteLine("{0} is equal to 5");
			}
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
12 is greater than 5

#4 Nested if...else Statement

Code - C# Programming

using System;
 
namespace Conditional
{
	class Nested
	{
		public static void Main(string[] args)
		{
			int first = 7, second = -23, third = 13;
			if (first > second)
			{
				if (firstNumber > third)
				{
					Console.WriteLine("{0} is the largest", first);
				}
				else
				{
					Console.WriteLine("{0} is the largest", third);
				}
			}
			else
			{
				if (second > third)
				{
					Console.WriteLine("{0} is the largest", second);
				}
				else
				{
					Console.WriteLine("{0} is the largest", third);
				}
			}
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
13 is the largest
Advertisements

Demonstration


C#`Programming if, if...else, if...else if and Nested if Statement