FunctionX - Practical Learning Logo

C++ Keywords: else

 

Overview

The else keyword is used to complete the if condition. It provides an alternative to a primary condition. The else keyword is never used by itself. It is used in the following context:

if(Condition)

    Statement1;

else

    Statement2;

The first if statement is used to evaluate a condition. If the condition is true, then it gets executed and the test ends. If the first condition is false, an else statement is used. When used by itself after an if condition, the else statement is used to process what ever would be negative but fits in the if condition. In this case, the else statement is used to embrace all false possibilities of the previous if condition. Here is an example:

#include <iostream>

using namespace std;



void main()

{

    unsigned int Miles;

    const double LessThan100 = 0.25;

    const double MoreThan100 = 0.15;

    double PriceLessThan100, PriceMoreThan100, TotalPrice;



    cout << "Enter the number of miles: ";

    cin >> Miles;



    if(Miles <= 100)

    {

        PriceLessThan100 = Miles * LessThan100;

        PriceMoreThan100 = 0;

    }

    else

    {

        PriceLessThan100 = 100 * LessThan100;

        PriceMoreThan100 = (Miles - 100) * MoreThan100;

    }



    TotalPrice = PriceLessThan100 + PriceMoreThan100;



    cout << "\nTotal Price = $" << TotalPrice << "\n\n";

}
Here is an example of running the program:
 
Enter the number of miles: 75

Total Price = $18.75

Press any key to continue

The else keyword can be preceded by an if statement. In this case, the else statement is made to process one or more particular negations of the previous conditions.

 

C++ Tutorial Copyright © 2001-2005 FunctionX, Inc.