Chapter 6. Decision and Control Statements

Once a decision was made, I did not worry about it afterward.

Harry Truman

Calculations and expressions are only a small part of computer programming. Decision and control statements also are needed, to specify the order in which statements are to be executed.

So far you have constructed linear programs, which are programs that execute in a straight line, one statement after another. In this chapter you will see how to change the control flow of a program with branching statements and looping statements . Branching statements cause one section of code to be executed or not, depending on a conditional clause . Looping statements are used to repeat a section of code a number of times or until some condition occurs.

if Statement

The if statement allows you to put some decision-making into your programs. The general form of the if statement is:

if (condition)
    statement; 

If the expression is true (nonzero), the statement is executed. If the expression is false (zero), the statement is not executed. For example, suppose you are writing a billing program. At the end, if the customer owes nothing or if he has credit (owes a negative amount), you want to print a message. In C++ this is written:

if (total_owed <= 0) 
    std::cout << "You owe nothing.\n";

The operator <= is a relational operator that represents less than or equal to. This statement reads, “If the total_owed is less than or equal to zero, print the message.” The complete list of relational ...

Get Practical C++ Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.