if Statement

In this chapter you will learn:

  1. How to use if statement
  2. else branch
  3. Nested if statement
  4. if statement without braces

if statement syntax

You can selectively execute part of a program through the if statement. Its simplest form is shown here:

if(condition) {
   statement; 
}

condition is a Boolean (that is, true or false) expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed.

The complete form of the if statement is

if(condition) {
   statement; 
}else {
   statement; 
}

The general form of the if using blocks of statements is

if(condition)//from   j a v  a 2  s  . com
{
    statement sequence 
}
else
{
    statement sequence 
}

if-else-if ladder. It looks like this:

if(condition)/*  j  av a  2s  . com*/
   statement; 
else if(condition)
   statement; 
else if(condition)
   statement; 
.
.
.
else
   statement;

Relational operators that can be used in a conditional expression.

else branch

if statement can have an else branch.

The following code prints out There is the value is less than 0.

using System;//ja v  a 2s.c o  m

class Program
{
    static void Main(string[] args)
    {
        int i = -1;

        if (i > 0)
        {
            Console.WriteLine("Here");
        }
        else
        {
            Console.WriteLine("There");
        }

    }
}

The output:

Nested if statement

You can nest if statements as follows:

using System;//from ja  v  a2 s.c  om

class Program
{
    static void Main(string[] args)
    {
        int i = 5;
        if (i > 0)
        {
            Console.WriteLine("more than 0");
            if (i > 3)
            {
                Console.WriteLine("more than 3");
            }
            else
            {
                Console.WriteLine("less than 3");

            }
        }
    }
}

The output:

if statement without braces

If if statement only has one statement we can omit the braces{}.

using System;//from ja v  a 2s  .c o m

class Program
{
    static void Main(string[] args)
    {
        int i = 5;
        if (i > 0)
            Console.WriteLine("more than 0");
    }
}

The output:

The good practice is to add the braces all the time.

Next chapter...

What you will learn in the next chapter:

  1. Get to know while loop syntax
  2. Use a while loop to calculate and display the Fibonacci numbers less than 50
Home » C# Tutorial » Statements
Comments
if Statement
while loop
do...while loop
for loop
foreach
switch
break
continue statement
goto statement
Xml Documentation