on Leave a Comment

C++ If, If-Else and Nested If-Else Statement

This article contains C++ If, If...Else and Nested If...Else Statement.

C++ If Statement

In C++, if statement can be implemented in two ways:

(1) Simple if statement 
(2) if...else statement

Simple if statement 

Syntax:

if(expression is true)
{
        //statements
}

Example:

int x=1;
if(x==1)
{
        cout<<"x equals 1";
}

Flow Chart

c++ if statement
Flow Chart of If Statement
Compiler checks if expression, if expression is true then compiler executes if code, otherwise compiler executes other statements below if body.

Program of C++ If Statement

/*C++ program to check even number using if statement*/
#include<iostream>
using namespace std;
int main()
{
    int n;
    cout<<"Enter a number : ";
    cin>>n;
    if(n%2==0)
    {
        cout<<n<<" is even number";
    }
    return 0;
}

OUTPUT:

Enter a number : 56
56 is even number


if...else statement

Syntax:

if(Test Expression)
{
       //Statements
}
else
{
       //Statements
}

Example:

int x=0;
if(x==1)
{
      cout<<"x equals 1";
}
else
{
      cout<<"x equals 0";
}
Flow Chart

c++ if else statement
Flow Chart of C++ If Else Statement

Compiler checks if expression, if true, then compiler executes if code, otherwise compiler executes else code.

Program of C++ If Else Statement

/*C++ program to whether a number is even or odd using if-else statement*/
#include<iostream>
using namespace std;
int main()
{
    int n;
    cout<<"Enter a number : ";
    cin>>n;
    if(n%2==0)
    {
        cout<<n<<" is even number";
    }
    else
    {
        cout<<n<<" is odd number";
    }
    return 0;
}

OUTPUT:

Enter a number : 27
27 is odd number


Nested if...else

If...else statement is useful to check two different possibilities. But if there is need to check more than two conditions, then nested if...else comes in use. 

Nested if...else statement is used to check more than two conditions.

Syntax:

if (testExpression1) 
{
   // statements
}
else if(testExpression2) 
{
   // statements
}
else if (testExpression 3) 
{
   // statements
}
.
.
else 
{
   // statements
}

Examples:

int x=0;
if(x<0)
{
    cout<<"x is less than 0";
}
else if(x==0)
{
    cout<<"x equals zero";
}
else
{
    cout<<"x is greater than 0";
}

Program of C++ Nested If Else

/*C++ program to check whether a number is less than 0, equal to 0, between 1 and 100 and greater than 100 using nested if else statement*/
#include<iostream>
using namespace std;
int main()
{
    int n;
    cout<<"Enter a number : ";
    cin>>n;
    if(n<0)
    {
        cout<<n<<" is less than 0";
    }
    else if(n==0)
    {
        cout<<n<<" is equal to 0";
    }
    else if(n>0 && n<=100)
    {
        cout<<n<<" values lies between 1 and 100";
    }
    else
    {
        cout<<n<<" is greater than 100";
    }
    return 0;
}

OUTPUT:

Enter a number : 101
101 is greater than 100

0 comments:

Post a Comment