www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C++ Tutorial - Lesson 5: Conditional Processing, Part 1

If/Else Statements and Relational Operators

by John Kopp

Support this site at no cost to you

Welcome to EasyCPlusPlus.com's C++ tutorial. This lesson introduces conditional processing. In previous tutorials, all the code in the examples executed, that is, from the first line of the program to the last, every statement was executed in the order it appeared in the source code. This may be correct for some programs, but others need a way to choose which statements will be executed or run. Conditional processing extends the usefulness of programs by allowing the use of simple logic or tests to determine which blocks of code are executed. In this lesson, a simple guessing game will be developed to illustrate the use of conditional execution.

The if statement is used to conditionally execute a block of code based on whether a test condition is true. If the condition is true the block of code is executed, otherwise it is skipped.

#include <iostream>
using namespace std;

int main()
{

    int number = 5;
    int guess;

    cout << "I am thinking of a number between 1 and 10" << endl;
    cout << "Enter your guess, please " << endl;
    cin >> guess;
    if (guess == number)
    {
        cout << "Incredible, you are correct" << endl;
    }

    return 0;
}

Please try compiling and executing the above. The "==" is called a relational operator. Relational operators, ==, !=, >, >=, <, and <=, are used to compare two operands. The program works, but it needs some improvements. If the user enters 5 as a choice, he gets back a nice message, "Incredible, you are correct". But what happens if the user puts in an incorrect choice? Nothing. No message, no suggestions, nothing. Luckily, for our program user, C++ has a solution.

The else statement provides a way to execute one block of code if a condition is true, another if it is false.

#include <iostream>
using namespace std;

int main()
{

    int number = 5;
    int guess;

    cout << "I am thinking of a number between 1 and 10" << endl;
    cout << "Enter your guess, please ";
    cin >> guess;
    if (guess == number)
    {
        cout << "Incredible, you are correct" << endl;
    }
   else
    {
        cout << "Sorry, try again" << endl;
    }

    return 0;
}
Previous Page       Next Page