Skip to Main Content
Practical C++ Programming, 2nd Edition
book

Practical C++ Programming, 2nd Edition

by Steve Oualline
December 2002
Beginner to intermediate content levelBeginner to intermediate
576 pages
14h 6m
English
O'Reilly Media, Inc.
Content preview from Practical C++ Programming, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Discovering Modern C++, 2nd Edition

Discovering Modern C++, 2nd Edition

Peter Gottschling

Publisher Resources

ISBN: 0596004192Supplemental ContentErrata Page