Selection Statement (if-else if-else) in c++

Selection Statement (if-else if-else) in c++


To understand this chapter you should know about Comparison Operators which is explained in previous chapter. Selection statements are very important in programming because we make decisions using it.

/* A simple c++ program example to demonstrate the if statement. */


// Program 1

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    if (first > second)
        cout << "first is greater than second." << endl;

    return 0;
}


/* A c++ program example to demonstrate if-else statements */


// Program 2

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    if (first > second)
        cout << "first is greater than second." << endl;

    else
        cout << "first is less than or equal to second." << endl;

    return 0;
}


/* A c++ program example to demonstrate if-else if-else statements. */


// Program 3

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
    cin >> first;

    cout << "Second "<< setw (2) << ": ";
    cin >> second;

    if (first > second)
        cout << "first is greater than second." << endl;

    else if (first < second)
        cout << "first is less than second" << endl;

    else
        cout << "first and second are equal." << endl;

    return 0;
}


Note: All the above three programs satisfies the condition that if first value
is greater then display the message "first is greater than second".

Question: When to use if, if-else and if-else if-else ?
Answer: It depends upon your program. The number of possibilities your program has. For example, in the above program there are three possibilities. The value could either be greater, smaller or equal. All these possibilities are covered using if-else if-else statements. Depending upon the possibilities you can add more "else if" statement before the final else statement. It is good programming to cover all the possibilities to make your program perfect.

In the next chapter we will learn about nested if statements.

Check out this stream