4.10 — Introduction to if statements

Consider a case where you’re going to go to the market, and your significant other tells you, “if they have strawberries on sale, pick some up”. This is a conditional statement, meaning that you’ll execute some action (“pick some up”) only if the condition (“they have strawberries on sale”) is true.

Such conditions are common in programming, as they allow us to implement conditional behavior into our programs. The simplest kind of of conditional statement in C++ is called an if statement. An if statement allows us to execute one or more lines of code only if some condition is true.

If statements typically take the following form:

if (expression) statement1;


if (expression) statement1;
else statement2;

When used in the context of an if statement, the expression is sometimes called a condition or conditional expression.

In both forms of the if statement, the expression is evaluated as a boolean value. If the expression evaluates to boolean true, then statement1 is executed. In the second form, if expression evaluates to boolean false, then statement2 is executed instead. Remember that any non-zero value will convert to boolean true, and any zero value will convert to boolean false.

Here’s a simple example:


The condition is true

Let’s examine how this works. First, we evaluate the conditional part of the if statement. The expression true evaluates to boolean true, so the statement attached to the if statement executes.

The following program works similarly:


b is false

In the above program, when the conditional expression evaluates, variable b evaluates to false. Consequently, the statement connected to the if statement does not execute, but the else statement does.

Executing multiple statements

In a basic form of an if statement presented above, statement1 and statement2 may only be a single statement. However, it’s also possible to execute multiple statements instead by placing those statements inside curly braces ({}). This is called a block (or compound statement). We cover blocks in more detail in lesson S.4.1 -- Blocks (compound statements).

An if or if-else using multiple statements takes the form:

if (expression)
    // etc
    // etc

For example:

This prints:

The condition is true
And that's all, folks!

A slightly more complicated example

The equality operator (==) is used to test whether two integer values are equal. Operator== returns true if the operands are equal, and false if they are not.

Here’s output from one run of this program:

Enter an integer: 4
The value is non-zero

Let’s examine how this works. First, the user enters an integer value. Next, we use operator== to test whether the entered value is equal to the integer 0. In this example, 4 is not equal to 0, so operator== evaluates to the value false. This causes the else part of the if statement to execute, producing the output “The value is non-zero”.

Boolean return values and if statements

In the previous lesson (4.9 -- Boolean values, we wrote this program using a function that returns a boolean value:

Let’s improve this program using an if statement:

Two runs of this program:

Enter an integer: 5
Enter another integer: 5
5 and 5 are equal
Enter an integer: 6
Enter another integer: 4
6 and 4 are not equal

Using if statements where the conditional expression is a function that returns a boolean value is common.

Non-boolean conditionals

In all of the examples above, our conditionals have been either boolean values (true or false), boolean variables, or functions that return a boolean value. What happens if your conditional is an expression that does not evaluate to a boolean value?

You already know the answer: If the conditional expression evaluates to a non-zero value, that value gets converted to boolean true, and the statement associated with the if statement executes.

Therefore, if we do something like this:

This will print “hi”, since 4 is a non-zero value that gets converted to boolean true, causing the statement attached to the if to execute.

Quiz time

Question #1

A prime number is a whole number greater than 1 that can only be divided evenly by 1 and itself. Write a program that asks the user to enter a single digit integer. If the user enters a single digit that is prime (2, 3, 5, or 7), print “The digit is prime”. Otherwise, print “The digit is not prime”.

Show Hint

Show Solution

4.11 -- Chars
4.9 -- Boolean values

11 comments to 4.10 — Introduction to if statements

  • Michael

    Hello there,
    Kindly assist me to solve my question.

    1. The criteria to qualify to get a loan from a bank is described as follows;
    First the applicant must have an account with the bank. If the applicant doesn't have an account with the bank, they are given the message"please open an account before applying"
    If the applicant has an account, the period of time is checked. If the period is less than 2 years,the applicant is given the message "you have not banked with us for more than 2 years" If the period is 2 or more years, the credit record is then checked. If the credit record is "bad" the applicant is given the message "your credit history is bad" if the credit history is "good" the applicant is asked the amount they would like to borrow. If the amount entered is above $250, the applicant is given the message "the maximum credit allowed is $250" If the amount is between  $5 to $250, the applicant is given the message "congratulations you qualify to get this loan" if the amount is below $5, the applicant is given the message "the amount is below the minimum limit"

    Write a program that uses the nested if statements to determine whether a person qualifies for a loan or not.

  • Executing multiple statements

    U forgot { after else in the example line 10

    • Alex

      It doesn't need it, since the statement that executes after the else is a single statement. I've updated the lesson to try to make this a bit more clear.

  • Jonathan

    I am new to C++ and I thought the question asked me to test all possible input so I wrote the following program lol. But I don't understand why when I "run without debugging", the program stops if my input is very large, and can anyone tell whether my code is correct or not??

    • * Initialize your variables with brace initializers.
      * Limit your lines to 80 characters in length for better readability on small displays.
      * There's no need for a header, move the function definitions above @main.
      * Use the auto-formatting feature of your editor.
      * Name your variables descriptively.
      * Use @std::sqrt instead of @sqrt.
      * Missing include to <cmath> (or <math.h>).
      * Floating point operations are prone to errors (ie. the result is not precise). This will cause your program to yield wrong results sooner or later. Use modulus instead.
      * Missing printed trailing line feed (Print a line feed when your program is done).
      * Use double literals for doubles (0.0 instead of 0).

      > the program stops if my input is very large
      Try changing the '\n' in line 36 to @std::endl. I'm guessing that you're stuck in an infinite loop and the output doesn't get flushed. @std::endl prints the text immediately, whereas the text might stay in memory for a while before it gets printed when using '\n'.

      • Jonathan

        thank you so much!

        • You're welcome, let me know how it went!

          • Jonathan

            This is my updated code base on your suggestion! Some of your suggestions I not quite understand (1) what is a trailing line feed? (2) what is double literal? Is it different from double?

            (3) One problem is that the program still stops in the middle when my input is large, for example using the number 2147483077:
            When 2147483077 is divided by 4345 the remainder is 1587
            When 2147483077 is divided by 4347 the remainder is 4219
            When 2147483077 is divided by 4349 the remainder is 3414
            When 2147483077 is divided by 4351 the remainder is 3517
            When 2147483077 is divided by 4353 the remainder is 175
            C:\Users\26jon\source\repos\Project1\Debug\Project1.exe (process 5792) exited with code -1073741571.
            Press any key to close this window . . .
            ^^^The program stops at "When"^^^

            • You're using recursion (A function calls itself (checkRemainder -> changeDiv -> checkRemainder -> ...)).
              Every call needs to store some information about that call. The memory available for these information is limited, causing your program to abort once it's filled up. You'll later learn about loops, loops should be used instead of recursion.

              > what is a trailing line feed
              If you're running Windows, you might not be familiar with using a terminal (console). You probably run the application through your IDE or by double clicking it.
              Linux/Mac tend to open a terminal, then run the application. The terminal stays open after the program has finished and can be re-used.

              Assuming '>' is the command prompt, running this program with './myProgram' will produce this output

              The command prompt is now at the end of the last line printed, that's ugly.
              Printing a line feed when your program is done solves this issue.

              Now we can continue typing in the next line.

              > what is double literal

  • syobi

    wrote isPrime(int x) that can also check other numbers too!

Leave a Comment

Put all code inside code tags: [code]your code here[/code]