Search

4.10 — Introduction to if statements

Consider a case where you’re going to go to the market, and your roommate tells you, “if they have strawberries on sale, buy some”. This is a conditional statement, meaning that you’ll execute some action (“buy some”) 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.

The simplest if statement takes the following form:

if (condition) statement;

For readability, this is more often written as following:

if (condition)
    statement;

A condition (also called a conditional expression) is an expression that evaluates to a Boolean value.

If the condition of an if statement evaluates to Boolean value true, then the subsequent statement is executed. If the condition instead evaluates to Boolean value false, the subsequent statement is skipped.

A sample program using an if statement

Given the following program:

Here’s output from one run of this program:

Enter an integer: 0
The value is zero

Let’s examine how this works in more detail.

First, the user enters an integer. Then the condition x == 0 is evaluated. 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. Since x has value 0, and 0 == 0 is true, this expression evaluates to true.

Because the condition has evaluated to true, the subsequent statement executes, printing You entered zero.

Here’s another run of this program:

Enter an integer: 5

In this case, x == 0 evaluates to false. The subsequent statement is skipped, the program ends, and nothing else is printed.

Warning

If statements only conditionally execute a single statement. We talk about how to conditionally execute multiple statements in lesson 5.2 -- If statements.

If-else

Given the above example, what if we wanted to tell the user that the number they entered was non-zero?

We could write something like this:

Or this:

Both of these programs are more complex than they need to be. Instead, we can use an alternative form of the if statement called if-else. If-else takes the following form:

if (condition)
    true_statement;
else
    false_statement;

If the condition evaluates to Boolean true, true_statement executes. Otherwise false_statement executes.

Let’s amend our previous program to use an if-else.

Now our program will produce the following output:

Enter an integer: 0
The value is zero
Enter an integer: 5
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 an if statement to a prior if-else, like so:

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

Note that you can chain if statements as many times as you have conditions you want to evaluate. We’ll see an example in the quiz where this is useful.

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

In this case, our conditional expression is simply a function call to function isEqual, which returns a Boolean value.

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?

In such a case, the conditional expression is converted to a Boolean value: non-zero values get converted to Boolean true, and zero-values get converted to Boolean false.

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.

We’ll continue our exploration of if statements in future lesson 5.2 -- If statements.

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
Index
4.9 -- Boolean values

38 comments to 4.10 — Introduction to if statements

  • BooGDaaN

    In section if-else, you need to update the code. At line 9

    is missing ';'.

  • Gustav

    Hi Alex!

    Just wondering if this code is acceptable

    Inside io.cpp

    • Fellow traveller

      Good try but nope. This would tell you that 9 is prime because it is neither 2 nor divisible by two without remainder.

      • Gustav

        How about this one?

        ~Cheers!

        • nascardriver

          `n` should be declared inside of the loop. Initialize your variables with brace initializers. Use ++prefix unless you need postfix++.

          You code now works, but it's slow. An easy optimization is to check for divisibility by 2 first, then use `i += 2` instead of `++i`. Every number that is divisible by an even number, would have been divisible by 2 already, so line 5 will never be true for anything except `i == 2`.

          • Gustav

            quick question, does it check for other numbers as well (numbers that divisible by 3 or any odd numbers)?

            • nascardriver

              The code you posted checks for divisibility by all numbers from 2 up to x/2.

              • Gustav

                Something like that?
                ~Cheers!

                • nascardriver

                  No, that won't work, you should've noticed that while testing.
                  When you initialize `i` to 2, and do `i += 2`, you're only testing for divisibility by even numbers.
                  `i` should be initialized with brace initialization to 3, check divisibility by 2 manually before the loop starts.
                  You can use another loop to test your code

  • Adam

    Can somebody please tell me why I'm getting told a ; is missing?

    #include <iostream>

    int main() {

        std::cout << "Please enter a number: ";
        int number{};
        std::cin >> number;

        if (number == 0) {
            std::cout << "The number is 0!";

        }
        else {
            std::cout << "The number you entered is not 0... I am most disappointed in you.";
        }

        std::cout << "Please enter another number: ";
        int number2{ 0 };
        std::cin >> number2;

        if (number2 == 0) {

            std::cout << "The number you entered is 0.";

        }
        else if (number2 > 0) {

            std::cout << "The number you entered is more than 0!";

        }
        else(number2 < 0) {

            std::cout << "The number you entered is less than 0!";

        }

    }

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

    Thanks.

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