C++ Condition Statements



The if statement

The if statement can cause other statements to execute only under certain conditions. You might think of the statements in a procedural program as individual steps taken as you are walking down a road. To reach the destination, you must start at the beginning and take each step, one after the other, until you reach the destination.

Program below illustrates the use of an if statement. The user enters three test scores and the program calculates their average. If the average equals 100, the program congratulates the user on earning a perfect score.


    #include <iostream.h>
    #include <iomanip.h>
    using namespace std;
    int main()
    {
    int score1, score2, score3;
     double average;
    
    // Get the three test scores
     cout << "Enter 3 test scores and I will average them: ";
     cin >> score1 >> score2 >> score3;
    
    // Calculate and display the average score
     average = (score1 + score2 + score3) / 3.0;
     cout << fixed << showpoint << setprecision(1);
     cout << "Your average is " << average << endl;
    
    // If the average equals 100, congratulate the user
     if (average == 100)
      { 
     cout << "Congratulations! ";
     cout << "That's a perfect score!\n";
     }
     return 0;
     }

    Output:
    Enter 3 test scores and I will average them: 80 90 70
    Your average is 80.0

    Output (if average==100):
    Enter 3 test scores and I will average them: 100 100 100
    Your average is 100.0
    Congratulations! That's a perfect score!

The if else statement

The if else statement will execute one set of statements when the if condition is true, and another set when the condition is false.The if...else statement is an expansion of the if statement.

This program uses the modulus operator to determine if a number is odd or even. If the number is evenly divisible by 2, it is an even number. A remainder indicates it is odd.


    #include <iostream.h>
    #include <iomanip.h>
    using namespace std;
     int main()
     {
    int number;
     cout << "Enter an integer and I will tell you if it\n";
     cout << "is odd or even. ";
     cin >> number;
    if (number % 2 == 0)
     cout << number << " is even.\n";
    else
    cout << number << " is odd.\n";
    return 0;
    }

    Output:
    Enter an integer and I will tell you if it
    is odd or even. 17
    17 is odd

The else part at the end of the if statement specifies one or more statements that are to be executed when the condition is false.

When number % 2 does not equal 0, a message is printed indicating the number is odd. Note that the program will only take one of the two paths in the if...else statement.


Ads Right