C++ if-else Statements

Advertisements
Advertisements

The if-else statement is a conditional statement with an optional else. The if statement executes a block of statements is the condition is true, but does not do anything when condition is false. The if-else block contains code for both true and false conditions.

Each of the block in if-else construct will be enclosed using braces( { } ). The general form of if-else is given below.

if(expression)
{
    statement1;
    statement2;
}
else
{
    statement3;
    statement4;
}

Clearly, the a program executes if block when expression = true and executes else block when expression = false.

Example Program: if-else

// example program to demostrate if-else 
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    //Variable Declaration
    
    int x,y,total;
    
    //Variable Initialization
    
    x = 100;
    y = 200;
    total = 0;
    
    //the if-else block
    
    if(x < 100)
    {
         total = x + y;
    }
    else
    {
         total = y - x;
    }
    
    //Printing the output
    
    cout << "Total =" << total << endl;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output:

Advertisements
Total =100

In the above example, the condition x < 100 is false. As a result, the else block is executed giving an output 100.

Types of if-else Constructs

There are several ways to construct if-else structure. Here is a list of possible constructs.

#1

if(expression)
{
    statement1;
    statement2;
}
else
{
    statement3;
}

#2

if(expression)
{ 
   if(expression)
   {
      statement1;
      statement2;
   }   else   {
      statement3;
   }
}
else
{
    statement4;
}

#3

if(expression)
{
           if(expression)
          {   
              statement1;
          }
           else
         {
             statement2;
         }
}
else
{
           if(expression)
          {
                statement3;
          }
           else
         {
               statement4;
         }
}

#4

if(expression)
{
}
else if(expression)
{
}
else if(expression)
{
}
else if(expression)
{
}

You can create different kinds of if-else constructs which one of the above construct as building blocks.


Bestseller

Object-Oriented Programming with C++ – 8th Edition

Object-oriented programming with C++, 8th edition is here with some valuable updates. The new edition helps students to assess their learning by answering questions based on learning outcomes. Objective-type questions and dry-run questions are introduced to make students exam ready. A new appendix on interview questions is for those seeking to join the industry. The book is designed for students studying at the undergraduate level. It provides all-inclusive concepts and programs on object-oriented programming with C++ as an implementation language.

  • 150+ multi-choice questions
  • 100+ dry-run exercises
  • 90+ interview questions
  • Two new projects and more

Advertisements
Advertisements
Advertisements