If Statement

c# if statement-A program cannot think if it cannot make a decision. C# allows you to execute codes if certain conditions are true or false. By using an ifstatement and specifying the condition that will execute the code, you can add  logic to your program. The if statement is a single-selection conditional statement which means that there will be no alternative codes to execute if a certain condition is not met.

The syntax of an if statement is as follows:

if (condition)
	code to execute;

Before an if statement can be executed, the condition is tested first. If the  condition results to true, then the following code will be executed. The  condition is in a form of a comparison expression. We use comparison operators to test if a condition is true or false. Let’s take a look at how we can use an  if statement inside a program. The following program will show the message “Hello World.” if the value of number is less than 10 and “Goodbye World.” if it is greater than 10.

using System;

namespace IfStatementDemo
{
    public class Program
    {
        public static void Main()
        {
            //Declare a variable and set it a value less than 10
            int number = 5;

            //If the value of number is less than 10            
            if (number < 10)                         
                Console.WriteLine("Hello World.");   

            //Change the value of a number to a value which     
            // is greater than 10                               
            number = 15;

            //If the value of number is greater than 10         
            if (number > 10)                         
                Console.WriteLine("Goodbye World."); 
        }
    }
}

Example 1 – Using the if Statement

Hello World.
Goodbye World.

Line 10 declares a variable named number with a value of 5. When we reach the  first if statement  in line 13, the program determines if the number is less than 10, that is if 5 is less than 10.  Logically, it results to true so the if statement’s corresponding statement to execute (line 14) will be executed resulting to printing the message “Hello World.”.

After that, we change the value of the number to 15  (line 18). When it reach the second if statement in line  21, it sees that 15 is indeed greater than 10 and executes the message “Goodbye World.”  in line 22.

Note that it doesn’t matter if you write the if statement in one line as in:

if( number > 10 ) 	Console.WriteLine("Goodbye World.");

As long as you have a single statement to execute and you terminate the statement with a semicolon, the above code is valid.

You can have multiple statements inside an if statement. You need to put curly braces to mark the start and end of  the set of statements to execute. Everything inside the curly braces is  considered the block or body of the if statement. Not  placing curly braces will lead to your program not doing what you expected. The following is the syntax of an if statement  with multiple statements in its block.

if (condition)
{
	statement1;
	statement2;
    .
    .
    .
	statementN;
}

Let’s look an example with this code snippet:

if (x > 10)
{
	Console.WriteLine("x is greater than 10.");
	Console.WriteLine("This is still part of the if statement.");
}

The code above will output the two messages if the value of x is greater than 10. If, for instance, we remove the curly braces and the value of x is not greater than 10 such as the following code snippet:

if (x > 10)
	Console.WriteLine("x is greater than 10.");
	Console.WriteLine("This is still part of the if statement. (Really?)");

We can see that the above code is read better if we put the proper intentions for the statements.

if (x > 10)
	Console.WriteLine("x is greater than 10.");
Console.WriteLine("This is still part of the if statement. (Really?)");

You can see that the second statement is actually not part of the if statement. The code will only print the second line because the value of x is less than 10 and the condition for the if statement will result to false. That’s why curly   braces are important. As a good practice, always write curly braces even if you only have one statement in the body of the if statement so whenever you want to add another statement inside it, you won’t forget to add curly braces which will result to errors which are hard to find.

One common mistake of beginners is putting a semicolon right after the right parenthesis of the if statement’s condition.  Consider the following example.

if (x > 10); 
	Console.WriteLine("x is greater than 10");

This will lead to the if statement having no  statements to execute. The second will be not part of the if statement. Although this would compile, your program will yield logic  errors. So always remember to not put a semicolon at the end of the condition of  an if statement because doing so will signify that the if statement’s code block has ended there.

Let’s take a look at another example of using if statements.

using System;

namespace IfStatementDemo2
{
    public class Program
    {
        public static void Main()
        {
            int firstNumber;
            int secondNumber;

            Console.Write("Enter a number: ");
            firstNumber = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter another number: ");
            secondNumber = Convert.ToInt32(Console.ReadLine());

            if (firstNumber == secondNumber)
            {
                Console.WriteLine("{0} == {1}", firstNumber, secondNumber);
            }
            if (firstNumber != secondNumber)
            {
                Console.WriteLine("{0} != {1}", firstNumber, secondNumber);
            }
            if (firstNumber < secondNumber)
            {
                Console.WriteLine("{0} < {1}", firstNumber, secondNumber);
            }
            if (firstNumber > secondNumber)
            {
                Console.WriteLine("{0} > {1}", firstNumber, secondNumber);
            }
            if (firstNumber <= secondNumber)
            {
                Console.WriteLine("{0} <= {1}", firstNumber, secondNumber);
            }
            if (firstNumber >= secondNumber)
            {
                Console.WriteLine("{0} >= {1}", firstNumber, secondNumber);
            }
        }
    }
}

Example 2

Enter a number: 2
Enter another number: 5
2 != 5
2 < 5
2 <= 5
Enter a number: 10
Enter another number: 3
10 != 3
10 > 3
10 >= 3
Enter a number: 5
Enter another number: 5
5 == 5
5 <= 5
5 >= 5

We used the comparison operators as a condition for each if statements. We asked an input from the user for two numbers that will be involved on the comparisons. The numbers will be compared inside every  if statements and print the corresponding message if the condition results to  true.

Note that conditions are boolean values which are results of a comparison  expression. Therefore, you can store the result of an expression in a boolean  variable and then use the variable as the condition in an if statement.

bool isNewMillenium = year == 2000;

if (isNewMillenium)
{
	Console.WriteLine("Happy New Millenium!");
}

If the value of year is indeed 2000, then the expression will yield true and be stored in variable isNewMillenium. We can use  the variable to determine if the if statement’s body will execute depending on whether the value of the variable is true or false.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *