The if statement is used to test a condition and offer a branch in the program depending on the result of the test. The next program shows how to use a basic if statement. This program asks the user to enter a number. If the number they enter is greater than 5, then the program outputs, "Your number is greater than 5." Otherwise, the program will not output anything.
Program 9.1 - Basic If Statement |
#include <iostream>
int main() |
Output |
In preceding program, immediately following the if statement is the condition (A > 5). A condition either evaluates to true or false. If the condition is true, then the line following the condition is executed. If the condition is false, the program will skip this line. Notice there is no semicolon after the if statement. The if statement technically ends after the cout statement.
Immediately following an if statement, we can add an else statement as shown in the next program. For the output, we run the program twice. In the first output, we assume the user enters a 9 at the cin statement. In the second output, we assume the user enters a 3.
Program 9.2a - If...Else Statement |
#include <iostream> |
Output 1 |
Output 2 |
With an if...else statement, only one of the two cout statements will execute - not both. The next program shows how to use the "is equal to" comparison.
Program 9.2b – Equal To Comparison |
#include <iostream>
cout << "Choose an option, 1 = square number, 2 = cube number :
";
if (Option == 1) else Total = Number * Number * Number; cout << "The answer is " << Total << endl; } |
Output
Choose an option, 1 = square number, 2 = cube number : 2 |
In the previous program, we assume the user entered 3 for the integer, and
chose option 2 to cube the number. Therefore, the
else statement executes since
the variable
Option is not equal to 1.
The following table shows all the comparison operators that can be used with an if statement.
Comparison Operators |
|
Operator |
Description |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
== |
Equal to |
!= |
Not equal to |
Important: It is a common
mistake to forget to use two equal signs
==
when testing for equality. If you accidentally use only one equal sign,
it will not cause a syntax error, but your program will probably not
work the way you were hoping. Using a single equal sign in a condition
is an assignment statement. As shown below, you will assign a value to
the variable. If the value you are assigning is 0, then the condition
evaluates to false. Otherwise, it evaluates to true. if (Option = 5) // This assigns 5 to Option and evaluates to true if (Option = 0) // This assigns 0 to Option and evaluates to false Again, always remember to use two equal signs == in you condition when testing for equality. if (Option == 5) // The proper condition tests to see of Option equals 5 |
The program below uses all of the comparison operators. In this program, we assume the user enters 75 for the value of A. The only condition that does not evaluate to true is: if (A <= 40).
Program 9.3 – All Comparison Operators |
#include <iostream>
using namespace std; |
Output |
In the preceding programs, we only have one cout statement to execute after each if statement. If you have multiple statements to execute on the condition of an if or an else, then you will need to use braces after these statements. Many programmers will always use braces for clarity. The next program shows how to use an if statement to ask the user what they want the program to do.
Program 9.4 – If...Else Statement with Braces |
#include <iostream>
using namespace std; |
Output |
In the previous program, notice that after each opening brace, the lines following are indented. Indentation after braces shows the different levels in your program – similar to indentation in a table of contents. Indentation will not change the way your program executes – it is intended to make the source code more readable. You may choose how many spaces to indent, or to insert a tab. Some editors like in Visual C++ will indent your program automatically when you insert braces.
When you have multiple conditions that all must be true, then you will need to use the logical AND (&&) operator within the condition. The next program demonstrates this.
Program 9.5a – Logical AND Operator |
#include <iostream>
using namespace std; |
Output A is between 1 and 10 |
In the previous program, both conditions must be true to execute the first cout statement –
(A >=1) and (A <=10). If one or both of the conditions are false, then the second cout statement will execute. Notice that each of the conditions is evaluated before the logical AND operator. Although it is not necessary, you can use addition parentheses in your condition as shown below.
if ((A >= 1) && (A <= 10))
When testing multiple conditions in which only one needs to be true, then you will need to use the logical OR (||) operator. This is typed using two vertical bars, or pipe symbols – above Enter on your keyboard. With a logical OR, at least one of the conditions must be true for the condition to evaluate to true. The next program demonstrates the logical OR.
Program 9.5b – Logical OR Operator |
#include <iostream>
using namespace std; |
Output Your number is odd. |
A third operator is the logical NOT (!). This will negate any condition it is placed in front of – i.e. the condition will evaluate to the opposite value. The example below demonstrates this.
if (!(A == 1)) // Evaluates to false if A is equal 1, and true otherwise
The words true and false may be used in a condition. This might be useful if you are testing a program and need a condition to always evaluate to true or false – you can temporarily substitute the condition with the word true or false. The following cout statement will always execute:
if (true)
cout << "This will always print";
The conditonal or ternary operator
allows you to put an
if...else statement in an assignment
statement. The statement below uses this conditional operator to convert the
variable Number to its absolute value.
Condition | Value if conditon true |
Value if condition false |
|
Number = | (Number > 0) | ? Number : -1 | * Number; |
After the equal sign on the above assignment statement is a condition (Number > 0). If the condition is true, then the expression after the question mark (Number) will be assigned to Number. If the condition is false, then the expression after the colon (-1 * Number) will be assigned to Number.
The next program demonstrates use of the ternary conditional operator.
Program 9.6 – Ternary Conditional Operator |
#include <iostream> int Donuts;
cout << "Please select an option\n";
cout << "2 = eat a half dozen donuts\n";
cin >> Choice; cout << "Have fun eating " << Donuts << " donuts.\n"; } |
Output 1 = eat a dozen donuts 2 = eat a half dozen donuts Your choice: 1 Have fun eating 12 donuts. |
What will each of the conditions evaluate to – true or false? Assume the following: X = 5, Y = 8, Z = 20 |
1. (X == 8) 2. (Z != 20) 3. (X == 3 || Z < 50) 4. (Z == 20 && Y < 10) 5. (!(Y >=6 && Y <=10)) 6. ((X != 5 || Y != 8) && Z == 20)) 7. ((X > 1 && Y > 10) || (Z <= 19 && Z >= 21)) 8. (X <= 5 && !(Z > 25)) 9. (!(Y > -5) || !(Z > -5)) 10. (Z = 15 && Y = 10) |
What will each of the following output?
11. int A = 1;
if (A > 0)
cout << "Yes";
else
cout << "No";
12. float B = 1.0, C = 2.0;
if (C <= B)
cout << "Apple";
else
cout << "Pear";
13. bool X = false, Y = true, Z = true;
if (Y && (X || Z))
cout << "Yes";
else
cout << "No";
14. int I = 4, J = -2, K = 0;
if (!(J < I) && !(K >= J))
cout << "red";
else
cout << "blue";
15. Write a program that prompts the user to enter an integer. Let the user know whether their number is evenly divisible by 2, 3, and 4.