The if Statement

The if Statement

The if statement is a fundamental control flow statement in C# that allows you to execute a block of code if a certain condition is true. Here’s the basic syntax of an if statement in C#:

if (condition)

{

    // code to execute if condition is true

}

Here’s an example of using an if statement in C#:

int num = 10;

if (num > 0)

{

    Console.WriteLine(“num is positive”);

}

In this example, the code inside the if block will only execute if the condition (num > 0) is true. If the condition is false, the code inside the if block will be skipped.

You can also use else and else if clauses to create more complex conditional logic. Here’s an example:

int num = 10;

if (num > 0)

{

    Console.WriteLine(“num is positive”);

}

else if (num < 0)

{

    Console.WriteLine(“num is negative”);

}

else

{

    Console.WriteLine(“num is zero”);

}

In this example, if the first condition (num > 0) is false, the second condition (num < 0) will be checked. If that condition is also false, the else block will execute.

You can also use logical operators such as && (and), || (or), and ! (not) to combine multiple conditions in an if statement. Here’s an example:

int num1 = 10;

int num2 = 5;

if (num1 > 0 && num2 > 0)

{

    Console.WriteLine(“both numbers are positive”);

}

In this example, the code inside the if block will only execute if both num1 and num2 are greater than 0. The if statement is a powerful tool that allows you to create programs that can make decisions based on specific conditions. By using if statements, you can write code that can respond to different situations and adapt to changing conditions.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Conditional Logic
Loops

Get industry recognized certification – Contact us

keyboard_arrow_up