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) true_statement;

For readability, this is more often written as following:

if (condition)
    true_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 true_statement is executed. If the condition instead evaluates to Boolean value false, then true_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 7.2 -- If statements and blocks.

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 7.2 -- If statements and blocks.

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

121 comments to 4.10 — Introduction to if statements

  • Dylan

    Here's my solution to question 1: It's similar to the provided solution, but has the user re-enter the number if it's greater than 9 or less than 0.

  • Waldo Lemmer

    1. Is it OK if main() consists of only function calls and nothing else?

    2. Question #1's solution, For advanced readers:
    >

    can be further compacted to:

  • Mal

    I think that question #1 could be answered in a number of ways. I just opted for the simplest (see below).  To enable students to generate code similar to the suggested answer I think the question needs to be a bit more specific - Use a function that uses a chain of if-else statements to compare the number the user entered to the prime numbers to see if there is a match.  The function should return a bool true/false to main().

  • Ahmed

    the first code can be reduced as well here's my answer:
    #include <iostream>

    bool isPrime(int x) {
         if (x % 2 == 0)
            return true;
        else
            return false;
    }
    int main() {
        std::cout << "Enter an integer: ";
        int x{};
        std::cin >> x;
        if (isPrime(x))
            std::cout << "The number is prime";
        else
            std::cout << "The number is not prime";
    }

    • Tim

      This code is unfortunately incorrect. This code works for if the number is odd or even but not for prime numbers. For example, let's assume the input is 4. In your isPrime() function, it would return true because 4 % 2 == 0 evaluates to true, thus, your program would say 4 is a prime number, which is incorrect. To make it faster, check out sieve of eratosthenes.

  • Forhad Rahman

    Why are you complicating the first problem with bool and even parameter within them? There is no need of bool type, just plain if-else works fine & keeps the program short & simple.

    • Concerned Web Person

      Why complicate with || when that hasn't yet been taught. It's good you know more than those who come with nothing, but we were promised unexplained features would not be used.

      • Forhad Rahman

        || is not complicating the thing, it's making the program more concise and understandable. Yes, I know these staffs already so...
        But when you'll learn more, you'll see which one is better ;)

        Cheers!

  • Pscyan

    Why this code is okay without the else statement after the last else if statement? When it's okay to skip the last  else and when it's not please tell me...

    • Szymon :)

      All of the possibilities have been gone over through, so if x isn't 2, or 3, or 5, or 7 it has to be (as the comment says) not a prime (withing the numbers 0 to 7).
      When you return something from a function, the function ends there. All the code under it gets skipped.

  • Mateusz Kacperski

    Hello :)
    I just wish to ask about second question.
    This is my code and what you think ?

  • SuperNoob

    Kindly tell me if I am doing this right. I mean the coding style and best practices.

    • Enderrrr

      Probably won't compile since isPrime won't return anything when x isn't a single digit number.

      • SuperNoob

        Non-1digit values are handled in the 30th line when isPrime is not even checked. My solution is a bit advanced for this lesson and it compiles and runs well. Feel free to run the code to remove your confusion.

  • anon

    #include <iostream>

    int main()
    {
        std::cout << "Enter a single digit integer:\n";
        int a{};
        std::cin >> a;

        if (a == 2, 3, 4, 7)
            std::cout << "the digit is prime";
        else
            std::cout << "the digit is not prime";

        return 0;
    }

    Pretty short, but is it better to build for modularity over what's short?

    • nascardriver

      Your condition is always true. `a == 2`, `3`, and `4` are discarded by the comma operator (Lesson 5.5). The condition that remains is `if (7)`. Your compiler should have warned you about this.

      • anon

        okay. I fixed

        #include <iostream>

        int main()
        {
            std::cout << "Enter a single digit integer:\n";
            int a{};
            std::cin >> a;

            if (a == 2)
                std::cout << "the digit is prime";
            if (a == 3)
                std::cout << "the digit is prime";
            if (a == 5)
                std::cout << "The digit is prime";
            if (a == 7)
                std::cout << "the digit is prime";
            else
                std::cout << "the digit is not prime";

                                                                                
            return 0;
        }

        • Chars

          I do not think this is correct.
          The way you have the "If"'s , each one of them will run independently of the other.
          So if i give the number 2 , then i will first get "the digit is prime" but then when it checks if the number (a ==7) it will also give me "the digit is not prime" since my number is NOT 7.

          I think you should put "else" before each "if" (not the first "if").

  • J34NP3T3R

    in this example

    if (x > 0)
        std::cout << "The value is positive\n";
    else if (x < 0)
        std::cout << "The value is negative\n";
    else
        std::cout << "The value is zero\n";

    can this end with an else if ?

    if (x > 0)
        std::cout << "The value is positive\n";
    else if (x < 0)
        std::cout << "The value is negative\n";

    or is this an error ?

  • peter

    [code]#include <iostream>

    int getNumber();
    bool prime(int x);

    int main()
    {
        int x{ getNumber() }; //Gets your height into variable x.
        int y{ prime(x) };   //Sends the height(x) to prime(int x) to check if you are above 140cm. The true or false value is returned from prime(int x) into variable y.

        if (y == 1)
            std::cout << "You are allowed to ride. ";
        else if (y == 0)
            std::cout << "No ride for you!";

        return 0;
    }

    int getNumber()
    {
        std::cout << "How tall are you? (Centimeters) \n";
        int x;
        std::cin >> x;
        return x;
    }

    bool prime(int x)
    {
        return (x > 140); //Returns true(1) if the height is above 140. If height is below 140 it returns false (0).
    }

    [code]

  • kio

    //please ignore this,

  • yeokaiwei

    I think the tutorial example may teach some odd if-else habits. Perhaps, if-loop as a bundle?

    • dignity

      Firstly, the reason the exercise got us to use that many if-else statements is to ensure that we understand the fundamental concept of if-else statements. Learncpp hasn't covered loops yet, the solution to the activity is the best we can do for what we've learnt so far.
      Also copying and pasting a program from: https://www.programiz.com/cpp-programming/examples/prime-number doesn't make you seem more intelligible, just saying.

  • David

    This worked, but should I be using else if instead?

    • Kevin Hasse

      In you case it doesn't matter and will work either way because you are only checking for specific values of x. (Is x exactly 2; Is x exactly 3; etc) Only one of those statements can be true at once. Consider something like this:

      If the user enters "2" now, both a and b will be executed. But in some cases you may want only one action to be executed. Thats when you write:

      Now if the user enters "2", only a will be executed; If he enters "4", only b will be executed.

      In the end it just depends on how you want your program to behave.

  • Here is my take on with prime number exercise

    • nascardriver

      `isPrime` should return `false/`true` based on `i`. There's no point in returning the number that the caller passed in.
      If `isPrime` returns a `bool`, it can be used for more than just printing.

  • kutlu

  • Martin

    Above no braces are used for single statements following if-else clauses, so I'd suggest to write the main() function in Quiz 2 as follows:

  • Tony

    In quiz one, why instead of:

    shouldn't we:

    ? Thanks for the great tutorials!

  • Shtimpo

    In regard of the above, I would like to remind the authors their own words from Chapter 0.1 of these tutorials:

    "We will also avoid ... the unexplained new concept, where a new concept that is integral to the example is introduced without any mention of what it is or how it works."

    At no point in these tutorials (up to this point) it was explained that return statements can be used in such way.

    I love these tuts beyond words, so none of the above is a complaining, just a reminder.
    I appreciate your work.

    • James Clarks

      This is not a valid code for prime number think something, else, finding weather the given number is a prime or not takes looping through numbers and that is not even intrudeced, yet.

      • nascardriver

        This function is from the quiz. The quiz asked for a function that checks for single-digit primes only. To check for all primes, you're right, we'd need a loop.

  • Aditya

    You wrote "(without changing the formatting)"  I think you should change this to "(without simply changing the formatting)".  I would say formatting was part of what was changed, but not the only thing that was changed.

  • Greg

    Minor typo in the solution for question #2.  The explanation text has "height < 140", when the program is checking for "height > 140".

Leave a Comment

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