Skip over navigation

Contents

Basic Commands in C++

Other Basic Statements

Problems

Problems

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:


int customer_age;
const int min_age = 18;
// irrelevant code omitted
if ((balance < min_bal) && (customer_age > min_age))
{ /* same code as above */ }

The "&&" is the logical AND operator. The logical OR, written as "||", is used in the same fashion. Both of these operators can be used to link logical tests.

One common kind of if-statement is used to assign a value to a single variable:


if (a > 2) 
	{b = 1;} 
else
	{b = a;}

There is, however, a more convenient syntax for this specific kind of if statement, the question-mark-colon operator. It is used as follows:


<variable> = (<test condition>) ? <first value> : <second value>;

The above if-statement would be written:


b = (a > 2) ? 1 : a;

Switch-statements

Sometimes the course of your program can change depending on one variable's value. In such an instance you could use nested if-statements:


if (val == 1)
	{ /* code here */ }
else {
	if (val == 2) 
		{ /* more code */ }
	else {
		if (val == 3)
			{ // etc.

You can see that this might get confusing very quickly. In such cases, you should use a switch-statement:


switch (val){
	case 1 : // code here
		break;
	case 2 : // more code
		break;
	case 3 : //etc.
		break;
	default: // default code
		break;
}

This is a much neater form that accomplishes the same goal. After each case, write the value in question followed by a colon and the code you want executed if the variable has this value. The separate break statements are necessary to stop the switch statement; if you leave out a break statement, execution of the code within the switch statement's braces will continue until a break command is reached. In case the value does not match any of the other cases presented, you should always include a default case at the end, as indicated. It's considered good style to break after the default code, although it is not strictly necessary.

Loops

Almost every program will repeat some segment of code in structures called loops. C++ provides three ways to do this: for-loops, while-loops, and do- loops.

For-loops are generally used when it is necessary to increment or otherwise modify a value after every pass. The structure is:


for(<initial values>; <condition to continue looping>; <update, or increment>)
{
	/* code to loop through */ 
}

The following simple example prints out the numbers 1 through 10:


for(int i = 1; i <= 10; i++)
	{cout << i << endl;}

Because there is only one line inside the for-loop's braces, the braces could be omitted. The for-loop initializes the value of i to 1, checks the test condition (which is initially true because 1 <= 10), and executes the code inside. After a pass through the loop, i is incremented (i++) and the test condition is checked again. This continues until the test condition is false. Note that the integer variable i is declared inside the for-statement. This is perfectly legitimate, but once the for-loop is finished, the variable i will no longer exist. Its scope is confined to the for-loop.

While-loops are much like for-loops, except that there is no initial value assignment or updating of variables. While-loops only check the condition before every pass:


while(<condition to keep looping>)
{
	/* code goes here */
}

Do-loops are almost equivalent to while loops, except that they will necessarily execute the code in brackets at least once before breaking:


do
{
	/* code here */
} while (<condition to keep looping>);

The test condition of a do-loop will not be checked until after the first pass through the loop.

In any kind of loop, the execution of a break command will halt the looping. Execution of a continue command will send the execution back to the top of the loop; and, in the case of for-loops, will also carry out the incrementing and updating.

Follow Us