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 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”.

Chaining if statements

Sometimes we want to check if several things are true or false in sequence. We can do so by chaining if statements together.

The less than operator (<) is used to test whether one value is less than another. Similarly, the greater than operator (>) is used to test whether one value is greater than another. These operators both return boolean values.

Here’s output from a few runs of this program:

Enter an integer: 4
The value is positive
Enter an integer: -3
The value is negative
Enter an integer: 0
The value is 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

25 comments to 4.10 — Introduction to if statements

  • Sinethemba

    I added a check to see if the number entered by the user was indeed a single digit. Is this fine?

      • Jose Chavez

        that's a good one, I did the same thing, I applied the python stuff although I really liked the authors' answer a lot since, it's quite simple.

        but clearly the difference of how they teach here btw  those YouTube channels is very obvious, here things are much more complex and simple to understand. I don't know how to express my gratitude to these people

  • BlueManedHawk

    I don't understand why we need to create a whole separate function in the quiz.  The following code works fine, uses less lines, and in my opinion is easier to read.  Obviously, if you were checking for single-digit primes multiple times in the same program, you would want to use a function, but it just seems so unneccessary.

    • Separating programs into smaller pieces increases reusability and in most cases readability. If you wanted to check if another number is prime, you'd have to repeat line 8, which is asking for trouble.

      - `main`: Missing return-statement.
      - If your program prints anything, the last thing it prints should be a line feed ('\n').

  • Parsa

    What if you want the function isPrime to return something so that the (for example) third else if executes?

    if you want the function to catch an error (for example you enter a number that isn't greater than one) and it returns something so that the third else if (or something) executes letting you know that the number you entered isn't greater than one?


    Great site by the way.

    • You haven't learned this yet

  • David

    Hi. What is the difference between declaring a variable using:
    int x;

    .. and declaring it with curly braces:
    int x{} ?

    and what is the advantage of using the braces, since both ways appear to have the same effect?

    • The value of `x` is undefined. Reading from `x` produces undefined behavior.

      `x`'s value is 0. Empty curly brackets initialize variables to their type's default value.

      See lesson 1.4 and 1.6 for more information.

  • Neon

    1) In the slightly more complicated example, there is a trailing << operator in line 10.

    2) Would you not consider it a best practice to always use curly braces for if/else statement bodies? If not, why? I usually find them very clarifying. For one-liners I use them on the same line, though.

    • Alex

      1) Typo fixed. Thanks!
      2) A lot of people advocate for always using braces because it makes your code more resistant to breaking if additional statements are added or removed. That's a valid viewpoint. However, plenty of other programmers would argue that doing so makes your code harder to read or more complicated than it needs to be. And since you can't assume braces exist, you need to check for them anyway. I think it's safer to do so than not, but personally I like to favor simplicity in this case.

  • alfonso

    Hi again! You did not teach "else if" but your solution to the quiz uses it. I tried to use only what appeared in the course by now in my solution.

  • 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]