Section 1 - The if Statement

3B.1.1 The Simplest Form of the if

To give your program the feel that there is an intelligent being inside of it -- a little person carrying on a conversation with a user -- you need some form of a conditional statement, otherwise known as an if statement.

The form of the statement is:

if ( <condition> )
<statement> ;

<some other statement>;
// etc.

If the <condition> is true, then <statement> is executed, otherwise it is skipped, and control passes to <some other statement>, the one that follows the if construct. Like the loops we will encounter, at most one statement can be controlled by an if.  However, this isn't a restriction since multiple statements can be bundled into a single compound statement, surrounded by braces:

if ( <condition> )
{
<statement> ;
<statement> ;
<statement> ;
}

The <condition> is similar to what goes inside a while or the test of a for loop (which we will cover soon). It is something that can either be true or false, like:

if ( x > y )
x = x + 4;

This says that if x is greater than y, then execute the next statement which adds 4 to  x. Otherwise skip that next statement and go on to the one following it.

#include <iostream>
using namespace std;

int main()
{
int age;


cout << "How old are you? ";
cin >> age;

if (age > 21)
cout << "Would you like a beer?\n";
cout << "Have a nice day!\n";
}

The output of run 1:


How old are you? 54
Would you like a beer?
Have a nice day!
Press any key to continue . . .

The output of run 2:

How old are you? 20
Have a nice day!
Press any key to continue . .
sunset2