Skip over navigation

Basic Commands in C++

Other Basic Statements

Problems

Other Basic Statements, page 2

page 1 of 3

if / else statements

You will often want the course of the program to change depending on the current value of one or more variables. Suppose you are writing an accounting program for a bank. You want to charge a customer if he or she has gone below his or her minimum balance of $500. For such a program you would want to use an if-statement. You might write something like the following:


const int min_bal = 500; // define constants and variables
const int penalty_charge = 5;
int balance;
/* irrelevant code omitted */
if (balance < min_bal) balance -= 5; // decrement by $5 if below balance

An if-statement is structured as follows:


if (<test condition>)
{<statements for when test condition is true>}

If the test condition is true, then code in brackets is executed. The example above uses the less-than symbol in the test condition. Other relational operators include > (greater than), == (equal to), >= (greater than or equal to), <= (less than or equal to), != (not equal to), and true or false (which evaluate accordingly). An exclamation point operates as a logical "not." That is, !true==false and !false==true. Multiple lines of code can exist between the brackets; if there's only one line then the brackets are not necessary.

Now suppose you want to print to the screen a message indicating whether or not the customer has gone below the balance minimum. You can use an if/else- statement in place of the if-statement:


if (balance < min_bal) {
	balance -= 5;
	cout << "This customer is below ""
	     << "the minimum balance!" << endl;
} 
else {cout << "This customer is fine.";}	

The code in the brackets after an "else" is executed when the test condition is false. Like the "if" statement braces are not necessary after the else statement if there is only one line of code there, as is the case here. Also note that the brackets can be on the same line or on different lines as the rest of the code; whitespace is ignored. Of course, the code in the brackets can contain more if/else-statements as is necessary. Such if-statements are referred to as being "nested."

The test condition can actually contain multiple tests, chained together with logical operators. Suppose you want to add the condition that the customer must be older than 18 to be fined if he or she has gone below the $500 minimum balance. Then you could write the following:

Follow Us