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 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 The value is 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

Question #2


How can the length of the following code be reduced (without changing the formatting)?

Show Solution


4.11 -- Chars
Index
4.9 -- Boolean values

64 comments to 4.10 — Introduction to if statements

  • Mike

    Hi.Found a typo. In the first sample program, instead of "printing you entered zero" it should be "printing The value is zero"

  • Yolo

    It's not really being said when do we need to use {} braces in the if statements and when not.
    For example in the first quiz answer, the compiler told me it found errors when i did not include braces {}.
    But when i typed your answer in the compiler, which is without braces, the compiler doesn't find any error.

    • someonecool

      As far as I know if there is only one instruction it doesn't have to be braces, if more u have to

    • Teal

      Previously it was explained that white space is ignored by the compiler in all but a few cases. In this case, this means that:

      is equivalent to:

      There exists, within languages based on C (including C++), a feature known as 'single-line if statements'. The compiler will treat the statement immediately following the conditional expression as the code to execute (or not, as the condition may be).

      For readability reasons, these are often formatted as in the first example. However, for debugging reasons it may be preferred to keep single-line if statements to one line (or to simply always use braces).

      For an insight into the possible complications of single-line ifs, consider the following:

      From the formatting, it might be hard to work out at a glance that the second statement is independent of the if statement, and will execute irrespective of whether the condition is met or not. As such, for the purposes of building good habits, it may be preferable to self-enforce the use of braces or, at the very least, be mindful of whenever you write or modify single-line ifs.

  • someonecool

    May I ask what's the different between these 2(I mean that '=')? And when I should use 1st and when use 2nd, even if I should use a 2nd(I mean with '=') at all, thank you in advice.

    For example:

    int userValue{ userInput() };

    and

    int userValue = { userInput() };

    2nd exmaple

    NOTIFYICONDATA nid{ sizeof(nid) };

    and

    NOTIFYICONDATA nid = { sizeof(nid) };

    • nascardriver

      I though there was almost no difference, but I was wrong. Thanks for making me look it up :D
      The first version performs direct initialization whereas the second performs copy initialization. As of now, you didn't learn enough to understand what this implies, but I'll leave an example that you can come back to after chapter 10 (Or even before that).

      Use the first version (Without `=`), it probably does what you want it to do.

      • someonecool

        Thank you for your response. Will do for sure, but how am I suppose to do it in this case and why? Which one should I use, simple variable, and simple fuction that gets 1 variable from user?

        int userValue{userInput ()};

        and

        int userValue = {userInput ()};

  • Chayim

    In answer of question 1:
      • What does "if" and "else if" <return true> and <return false> in bool isPrime function do? What is the outcome of true and false in function "main" ? Function "main" has an "if" and "else” function for Boolean output.
      • Why does "return false" in bool function not have a pre "else" function to outcome of "false" like any < if else > function?

    • nascardriver

      See lesson 2.2 about return values.
      `isPrime` returns the value to the caller (`main`), where it can be used (eg. as the condition of an if-statement).
      I don't understand your second question. Can you provide an example of what you're expecting?

      • Chayim

        I meant to ask:
        In "bool isPrime(int x)"
            — return false; // if the user did not enter 2, 3, 5, 7, the number must not be prime
        } —
          Why is it not "else return false;"

        But I got the answer in question 2, that Boolean function does not need “if else” and it’s able to go straight to "return".

  • Chayim

    Why use < if ! > ? if I can simply use < else >

    • nascardriver

      If you don't want to handle the true-case, there's no reason to add one.

      vs

  • Bruno

    Typo at the start

    "The simplest kind of of conditional..." Two "of"

  • Tom Bauer

    I just wanted to know what you think about this solution.

    [code]

    'Quelle.cpp'

    #include <iostream>
    #define PEAN "Please enter a number: "

    int duoble(int x)
    {
        return x * 2;
    }

    int multiply(int x,int y)
    {
        return x * y;
    }

    int subtract(int x,int y)
    {
        return x - y;
    }

    int divide(int x,int y)
    {
        return x/y;
    }

    int add(int x, int y)
    {
        return x + y;
    }

    int userinput()
    {
        std::cout << PEAN << '\n';
        int input{};
        std::cin >> input;
        return input;
    }

    int userinput2()
    {
        std::cout << "Please enter another number: "<< '\n';
        int input{};
        std::cin >> input;
        return input;
    }

    -------------------------------------------------------------------------

    'main.cpp'

    #include "Host.h"

    void bothnegative()
    {
        std::cout << "Both numbers are negative." << std::endl;
    }

    void twobiggerzero()
    {
        std::cout << "Your second number is positive." << std::endl;
    }

    void twolesserzero()
    {
        std::cout << "Your second number is negative." << std::endl;
    }

    void onebiggerzero()
    {
        std::cout << "Your first number is positive." << std::endl;
    }

    void onelesserzero()
    {
        std::cout << "Your first number is negative." << std::endl;
    }

    void onebiggertwo()
    {
        std::cout << "Your first number is greater than your second." << std::endl;
    }

    void twobiggerone()
    {
        std::cout << "Your second number is greater than your first." << std::endl;
    }

    void notsamenum()
    {
        std::cout << "You entered two different numbers!" << std::endl;
    }

    void samenum()
    {
        std::cout << "You entered the same number!" << std::endl;
    }

    bool boolerx(int x)
    {
        return (x < 0);
    }

    bool boolery(int y)
    {
        return (y < 0);
    }

    void boolertestnegative(int x)
    {
        if (x == 1) std::cout << "Both numbers are negative." << std::endl;
    }

    void boolertestpositiv(int x)
    {
        if (x == 0) std::cout << "Both numbers are positive." << std::endl;
    }

    int main()
    {
        int x = userinput();
        int y = userinput2();
        if (x == y) samenum();
        else notsamenum();
        if (x < y) twobiggerone();
        if (x > y) onebiggertwo();

        if (boolerx(x) == boolery(y)) boolertestnegative(boolerx(x));
        else if (x < 0) onelesserzero();
        else if (y < 0) twolesserzero();
        if (boolerx(x) == boolery(y)) boolertestpositiv(boolerx(x));
        else if (x > 0) onebiggerzero();
        else if (y > 0) twobiggerzero();        
    }

    [code]

    • nascardriver

      Closing code tags use a forward slash [/code].

      - Avoid preprocessor macros. They can break code and are harder to understand than C++.
      - Initialize variable with brace initialization for higher type safety.
      - Use '\n' unless you need `std::endl`, it's faster.
      - `boolerx` and `boolery` are identical. Variable names don't matter.
      - Avoid abbreviations.
      - You names are difficult to read. Consider camel case or underscores.

  • Tony98

    Hi (again), I've done the exercise in a different way since I know about operator "||" (I've previously done this tutorial but came back since I had problems and needed a fresh restart). Since I couldn't do it like you did I've done it in a different way. Could you please tell me if everything's alright or whether I should have proceeded in a different way? Thank you for the hard work!

  • Kermit

    here is quiz answer

    • nascardriver

      Good job!

      By merging `print` and `isPrime`, you're decreasing reusability, ie. you can no longer check if a number is prime without printing it. Have a look at the solution in case you didn't understand the return.

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