2.6 — Boolean values and an introduction to if statements

In real-life, it’s common to ask or be asked questions that can be answered with “yes” or “no”. “Is an apple a fruit?” Yes. “Do you like asparagus?” No.

Now consider a similar statement: “Apples are a fruit”. Is this statement true or false? It’s clearly true. Or how about, “I like asparagus”. Absolutely false (yuck!).

These kinds of sentences that have only two possible outcomes: yes/true, or no/false are so common, that many programming languages include a special type for dealing with them. That type is called a boolean type.

Boolean variables

Boolean variables are variables that can have only two possible values: true (1), and false (0).

To declare a boolean variable, we use the keyword bool.

To initialize or assign a true or false value to a boolean variable, we use the keywords true and false.

Just as the unary minus operator (-) can be used to make an integer negative, the logical NOT operator (!) can be used to flip a boolean value from true to false, or false to true:

Boolean values are not actually stored in boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0. Similarly, when boolean values are evaluated, they don’t actually evaluate to “true” or “false”. They evaluate to the integers 0 (false) or 1 (true).

Consequently, when we print boolean values with std::cout, std::cout prints 0 for false, and 1 for true:



If you want std::cout to print “true” or “false” instead of 0 or 1, you can use std::boolalpha:

This prints:


You can use std::noboolalpha to turn it back off.

A first look at booleans in if-statements

One of the most common uses for boolean variables is inside if statements. 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, expression is evaluated. If expression evaluates to a non-zero value, then statement1 is executed. In the second form, if expression evaluates to a zero value, then statement2 is executed instead.

Remember that true evaluates to 1 (which is a non-zero value) and false evaluates to 0.

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 value 1, which is a non-zero value, so the statement attached to the if statement executes.

The following program works similarly:


b is false

In the above program, when the condition evaluates, variable b evaluates to its value, which in this case is false. False evaluates to value 0. Consequently, the statement connected to the if statement does not execute, but the else statement does.

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

Boolean values are often used as the return values for functions that check whether something is true or not. Such functions are typically named starting with the word is (e.g. isEqual) or has (e.g. hasCommonDivisor).

Consider the following example, which is quite similar to the above:

Here’s output from one run of this program:

Enter an integer: 5
Enter another integer: 5
5 and 5 are equal

How does this work? First we read in integer values for x and y. Next, the conditional expression “isEqual(x, y)” is evaluated. This results in a function call to isEqual(5, 5). Inside that function, 5 == 5 is evaluated, producing the value true (since 5 is equal to 5). That value is returned back to the caller. Since the conditional evaluated to true, the statement attached to the if executes, producing the output “5 and 5 are equal”.

Boolean values take a little bit of getting used to, but once you get your mind wrapped around them, they’re quite refreshing in their simplicity!

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 evaluates to a non-zero value, then 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.

Inputting boolean values

Inputting boolean values using std::cin sometimes trips new programmers up.

Consider the following program:

Enter a boolean value: true
You entered: 119

Wait, what?

It turns out that std::cin only accepts two inputs for boolean variables: 0 and 1 (not true or false). Any other inputs will cause std::cin to silently fail. In this case, because we entered “true”, std::cin silently failed and didn’t assign a value to b. Consequently, when std::cout printed a value for b, it printed whatever uninitialized value was in variable b. Garbage!


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

Hint: Use if statements to compare the number the user entered to the prime numbers. Use a boolean to keep track of whether the user entered a prime number or not.

Quiz answers

1) Show Solution

2.7 -- Chars
2.5 -- Floating point numbers

347 comments to 2.6 — Boolean values and an introduction to if statements

  • #include <iostream>

    int main()
        int prime(int); // forward declaration of function ‘prime’

        std::cout << "enter a number: " ;
        int num;
        std::cin >> num; // Input a value

        //Check whether the number is prime

            std::cout << "Entered number is a prime"<<std::endl;
            std::cout << "Entered number is a composite" <<std::endl;
        return 0;

    int prime(int num)
        if(num==2 || num==3 || num==5 || num==7) // Check of prime for single digit
            goto label;

        else if(num%2 == 0 || num%3 == 0 || num%5 == 0 || num%7 == 0)
            return 0;

        label: return 1;


    Dear Alex, please have a look at this above piece of code and let know your comments.

    Thank you in advance.

    • Alex

      The main function looks fine.

      The prime function has some issues. First, it should return a bool, not an int. Second, there’s no point in using a goto. Just return true from within the if statement (return statements don’t have to be at the bottom of the function). Third, the modulus checking part of the else if statement isn’t logically necessary since it’s essentially doing the inverse of the above. You could remove the second if and it would perform identically.

      • bool prime(int num)
            if(num==2 || num==3 || num==5 || num==7)
                return 1;

            else if(num%2 == 0 || num%3 == 0 || num%5 == 0 || num%7 == 0)
                return 0;


        Thank you Alex. Please have a look at the ‘prime’ function, the first two comments are fixed. Coming to the third one, the else if statement is written to check whether the entered number is prime or not for any number of digits and not confined to the single ones. Eg: I don’t know whether 27329 and 103471 are prime or not, I enter these numbers and the result show that they are prime and which indeed are. Though this is not the part of the asked assignment, I just have included.

        My question is, Is this approach right instead of loops? or definitely there must be a better simplest way, if any please let know.

        • Alex

          The else statement fails if you enter 121 (it says it’s prime, it’s not). That’s why I kept the problem simple: so you could solve it simply. Writing a program to determine if any number is prime is more difficult and outside the scope of these tutorials (that’s more of an algorithms challenge).

          Also, your new function doesn’t return a value at all if neither of the if statements are true. That will lead to undefined results.

  • Maine

    Why is it possible to declare true/false using a variable?

    • Alex

      I’m not sure I understand what you’re asking.

      Variables can hold values. Integer variables hold integer values. Floating point variables hold numbers with decimals. Boolean variables hold a true/false value (1 or 0).

  • Zero Cool

    Here is my solution for the Quiz (I did it for the first 10000 numbers).






    I apply some advanced topics that you will find in future chapters. But I think I did a good job using modularity.

  • Dat coder

    Is switch better in this case?

  • Marean

  • Hema

    Could you explain the concept of Boolean in detail? it is confusing.

  • himanshu

    hey alex!
    what is system("pause")

    • Alex

      This asks the operating system to execute the “pause” command, which, on some systems, will cause the console to wait for the user to press a key before continuing.

      It’s basically a non-portable way to force the program to stop executing temporarily.

      There are better methods, such as the one I show in lesson 0.7.

  • himanshu

    WHAT IS "boolalpha()"NOT"boolalpha"

    does it possible to create
    a program .
    which tell us about a number it is even
    or odd.
    does we need if function or switch again & again to infinity..

    • Alex

      I’m not sure what you’re asking about boolalpha. boolalpha isn’t a function, it’s a format specifier.

      It is possible to create a program that tells you if a number is even. The modulus operator (%) is perfect for this. See chapter 3.2.

      • himanshu

        when i write boolalpha in code::blocks in the option boolalpha() comes

        • Alex

          Oh, I see. std::boolalpha IS a function, but when you use it, you use it without the parenthesis.

          (For advanced readers, we’re passing boolalpha as a function pointer to operator<< rather than calling the function ourselves)

  • Amandeep Kaur . 4261652

    a program to read and display Boolean functions.
    my code
    using namespace std;

    int main()
        bool boolvalue;

        cin>> boolalpha>> boolvalue;
        cout<< boolalpha<<boolvalue;

    but I want that if input is 0 then it shows false and for 1 it will show true but in my output only true is coming.

  • Amandeep Kaur . 4261652

    I did like this but having an error in operand .
    using namespace std;
    bool is6digits (string pin)
        bool status = true;
        if (pin.length() !=6)
            status = false;

    int main()
        string PIN;
        cout<<"Enter a 6 digit PIN number: ";
        cin >> PIN;

        if (is6digits(PIN) ==1)
            cout<<"PIN Accepted.";
            cout <<"PIN Denied.";

    I tried to use char instead of string bt again having the error .
    help me with this

    • Alex

      Two things:
      1) You should #include string.
      2) is6digits() is declared to return a bool, but it doesn’t actually return a value. You should return the status variable.

  • Amandeep Kaur . 4261652

    a program to test if Pincode is 6 digit or not using Boolean functions
    how to define the function ?

    • Alex

      Sounds like a homework assignment. Tell me what you think it should be. Consider what the program needs to accept as input and output.

  • Cotrim

    if any one is interested I wrote on that actually tests any number to be prime or not (at least it was successful in all my tries xD)

    Suggestions are welcome ofc!





    Noticed after posting that I’m actually making 2 function calls instead of one, should have created a variable and put the result of TestIfPrime in it then created the display ifs. If I’m reading it right, originally it had no guard for 0, 1 or negative numbers only after I started writing this reply that I noticed that problem and changed the TestIfPrime to int, but then again I think I could have made it with bool return exactly the same way ><

  • Axel Martinez

    How is my solution? What improvements could be made? I know my solution didn’t use bool, but I just wanted to come up with a more universal solution. Not just a check for every single digit number.

    #include <iostream>
    #include <stdint.h> // for fixed width integers
    #include "functions.h" // Ignore this directive. I was practicing with the other header files from previous lesson
    using namespace std;

    int main()
    int x;
    cout << " enter a number" << endl;
    cin >> x;
    int z = x/2;
    int c = z *2;

    if (c !=x)
        cout <<"the number entered is prime" << endl;
    else if ( c == 1)
        cout << "the number entered is prime" << endl;
        cout << " the number entered isn’t prime" << endl;

    system ("pause");
    return (0);


    • Alex

      Well, the main problem is that it doesn’t work. If you enter 9, it tells you the number is prime.

      Other issues:
      * There are no comments
      * Use of std:: is preferred over a using statement
      * x should be declared as close to the first use of x as possible
      * You use a system command that is non-portable.

  • Breadcrumbs

    I might’ve gone a bit over the top, but this is my take on the Prime Number checker.

    Any thoughts?

    • Alex

      Generally looks okay. A few thoughts:
      1) isPrime() shouldn’t determine whether the number is prime, not do the printing to the screen itself.
      2) You should return true or false instead of 1 or 0.
      3) Your x++ doesn’t need to be in its own block (not wrong, just unnecessary since it’s a single statement)

      • Breadcrumbs

        Thanks for the pointers, made some of the changes. Just one thing: what do you mean by "its own block"? Where else should I put x++?

        • Alex

          By it’s own block, I meant this:

          Since x++ is a single statement, you could just do this:

          and it will work fine without making your code take two additional lines.

      • saltolog

        I’ve compared Breadcrumbs attempt and mine. I’ve looked for a way to measure CPU time using his and mine code. His code finds out if certain number is prime in about
        6.23 sec and mine in 8.39 sec. I can see why and here comes my question - Is he just more intelligent or does better planning really come with practice. My program is about 2 sec slower doing something so trivial. Will I really be able to make faster, most complicated programs than for example this guy just by practicing more?

        • Alex

          Better planning and the ability to write more straightforward code does come with practice. Learn from what others do well, as well from your own mistakes, and you will get better over time.

  • Nicolas

    Hello Alex,
    I did the quiz and I got the following error:

    ---- Build started: Project: HelloWorld, Configuration: Debug Win32 ----
    1>main.obj : error LNK2011: precompiled object not linked in; image may not run
    1>C:VC2017ProjectsHelloWorldDebugHelloWorld.exe : fatal error LNK1120: 1 unresolved externals
    1>Done building project "HelloWorld.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========  

    Since I saw nothing wrong with my code(which I dont have cause I deleted it)  I copy and pasted your quiz answer and it still gave me the same error. Any idea why?

    • Alex

      Seems like a Visual Studio IDE issue related to pre-compiled headers or the way your compiler is configured. Have you upgraded from an older compiler? Maybe some of your library paths are incorrect or something. I’d try doing a full uninstall and reinstall of Visual Studio to see if that fixes.

  • Hi again,

    I took a slightly different approach to the quiz as follows:-

    Although I may have overdone it a bit on the parentheses 😉 , ideally I would also like to have included a check on the input to make sure it was in range (between -10 and 10) to give the user an opportunity to start again, but that’s just me, I’m a belt and braces guy 🙂

    What do you think

    • Oops!, I’m sorry, I messed up, after checking a few sites about prime numbers I should have re-worded my comment about setting a range to say "in between 1 and 10", apparently, a prime number is a positive integer above 1 that can only be divided by 1 or itself (which makes sense)

      Sorry about that,

    • Alex

      I think this is great. I didn’t use this solution only because I haven’t talked about logical OR yet. But once you know what logical OR is, this is a better solution.

      • Dammit!, I’m sorry Alex,

        I was doing a tutorial called learn C++ in 21 days previously by some fella and freaked out when it hit classes, functions and overloading it’s one of those tutorials that starts simple but moves very fast (too fast for my old brain)

        I didn’t mean to introduce an advanced concept at this stage, I thought that the ideas in my listing had already been covered (e.g. forward declarations and logical operators) I am sorry about that.


  • the confused coder

    Hello, I can’t figure out why my code doesn’t function like yours does. When I build and run, I can type the 4 prime numbers and I can type any other number that isn’t and it always will display "this number is prime."
    Heres the code:

    Why is this happening?

    • Alex

      You have extraneous semicolons after your if statements:

      Otherwise it parses like this:

      • the confused coder

        Awesome, that worked thank you. And 1 more thing, could you explain why we add

        at the end of the bool statement?

        • Alex

          Consider how the logic of this function works. The user’s input must be either prime or non-prime. In this function, we test to see whether the user entered a prime number. If we’ve gone through all of the prime numbers and none of those matched the user’s input, then the number they entered must be non-prime.

          That return false at the end is the function telling the caller that the number must be non-prime, because none of the tests for whether the number was prime succeeded.

  • astro

    thanks for the tutorials. i have a slight problem, when entering the numbers 2,3,5 both texts "prime" and "no prime" are displayed in my program, for some reason it doesn’t appear on the number 7. non the less anyone have any suggestions.

    • Helper

      Your last if statement has else statement nested with in it. This causes anything to be not prime if it is not equal to 7

    • Kevin

      as "helper" said, ur problem is not putting the curly braces "{}" in each statement. Make sure to always use curly braces.

    • Alex

      This is happening because the else statement is only being attached to the last if statement, so it will always execute so long as a does not equal 7.

      You can solve this by using a series of if/else statements (if (a==2) … else if (a==3) … else if (a==5) … else if (a==7) … else …).

      A few other notes:
      1) Variable a in main() isn’t doing anything and should be removed
      2) Parameter a in instructions() should be a local variable, not a parameter (move it inside the function body)
      3) prime() should return void since you don’t return a value (or need to)

  • Timothy Davis

    just ignore the sleep thing, i just use it to keep the program open for couple secs so i can see what happens, anyways did i do my homework correctly teacher ?

  • Jim Smith

    This is my homework.

  • Stelios

    in the quiz why cant we just use int isPrime(intx)
    and why do you say return false in the answer of the quiz question

    • Alex

      You could use int as the return type instead of bool, but that doesn’t express your intent as well. You should use bool when you mean true/false, and int when you’re actually returning an integer value.

  • rick

    hey! 🙂

    first of all i gotta say - this tutorial is really awesome and i learn very much from it! 🙂 keep it up!

    so i did the quiz an i end up with a problem in my isPrime function that i do not understand. every number i pass seems to be a non-prime number 🙂 is it impossible to use || or && in if? :/

    here we go:

  • Kyle

    Hey Alex! Thanks for these tutorials. I’ve been noticing that while I can accomplish the end goal, I always write it much differently than you do. For example, I can’t make my mind think to have the isPrime() func just return true or false to main(), but instead I have isPrime() do all the heavy lifting.

    Is this a problem I should worry about that might cause issues down the road when I reach more complex stuff? I taught myself basic coding on those TI89 calculators, so I never had a good tutorial or rules to follow. Thus, the way I fundamentally piece my solution together in my head is… off.

    Also a side question: is it a bad idea to forward declare main() or to call it more than once like I have below (just added functionality to check more than one number)?

    Anyway, heres my code:

    • Alex

      Figuring out how to break down your program into functions is something that’s a bit of an art. It takes practice, and you’ll likely do it wrong many times before you learn how to do it right. Just keep practicing, and it will come with time. Remember the “functions should do one thing” guideline. Your isPrime() does two things: determines if something is prime, and then prints whether it is prime or not. That violates the “one thing” guideline.

      It is not a good idea to call main() more than once. If you want to have something execute more than once, you should generally use loops (covered in chapter 5).

  • Alana Howard

    I went about writing this code tooooootally unlike the answer, although the program was debugged and runs effectively, which is cool cause I was worried I would just rip my hair out before peeking at the answer.  I made a header file titled IsPrime which defines 4 variables w,x,y,&z as the single digit primes.  I included this in my "PrimeProgram.cpp"

    Is this way of doing it problematic and a bad habit that I don’t know I’m starting, or is it just a different approach that is okay to use?

    • Alex

      Yes, it’s problematic for several reasons, mainly because it doesn’t work. 🙂 If you enter 8, it says 8 is prime, when it’s clearly not.

      Outside of the not working issue, here’s other issues I’d identify as not good:
      1) You’re defining variables w, x, y, and z as global variables when that’s not necessary here. You could just use literal numbers 2, 3, 5, and 7 instead. The variables are extraneous.
      2) You also define v as a global variable and then shadow it with a local variable inside main (get rid of the global int v).
      3) You’re using the comma operator in a way that doesn’t make sense (chaining expressions via comma inside a conditional doesn’t do what you might expect).
      4) You’re using = instead of == in main() (setting w, x, y, and z to the user’s input instead of doing a comparison)
      5) You defined isPrime() but then you never call it.

      The overall structure of your program is good (have an isPrime function that returns a bool indicating whether the number is prime) and the top of your main is good, but things go sideways from there. Keep at it. 🙂

    • Alana Howard

      I guess the whole thing got sideways when the isPrime function gave various errors when I tried to call it, saying that it wasn’t allowed and incompatible with the bool function.  I’ll implement your suggestions and rewrite it(hopefully correctly) and hopefully it becomes similar to the given answer, if not almost identical 😀 I also should have checked the non prime numbers more thoroughly - when the screen printed it I just kind wishfully assumed I was reading "not prime" because I was so excited it was running at all. ^_^ Thanks for the help!

    • Alana Howard

      Okay, so after much brain wracking and having to reorganize to as simple as possible(difficult for me, I make all things complicated :)), this is what I ended up with, I tested each number to ensure it worked, and it does!  I was curious if the bool == instruction returns true if equal and false otherwise, is there a necessary reason that true and false were defined in the quiz answer?

      • Alex

        Yes, operator== returns true if the operands are equal and false otherwise.

        I wrote the quiz answer to be as easy to follow as possible for users still getting familiarized with bool, true, and false. Plus we haven’t covered logical OR yet. Experienced programmers would write isPrime() more like you did.

  • One Manual

    That solution is so $%&/%/$#%(**). In 1.4 Quiz (1e) it is implied that only one of 2 return values is returned, only the first one (5 in that particular point). Ergo i smashed my head in the keyboard trying to find a solution compatible with the things i have been learning.

    Apparently there CAN BE more than 1 return value in a boolean function. Im confused now.

    Also please point out that the program in this quiz doesnt have to take in account ALL the prime numbers, only the 4 written there.

    • Alex

      My apologies for your head and your keyboard. I updated the text of lesson 1.4 to try and clarify a bit better. A function can only return a single value back to the caller. However, the function can use whatever logic it wants to determine which specific value to return. It can pick a single value from a set of values, or it can use an if statement to conditionally return a value. I also updated the example in this lesson to better indicate this.

      I’ve also updated the quiz to be clearer that you only need to take into account the single digit prime numbers.

  • Felipe

    isn’t this better?

    • Alex

      Yes, experienced programmers would get rid of the temporary variable in this case and do as you suggest.

      My goal here is to try and make the solution as understandable as possible, not as efficient as possible. For that reason, I moved the call to isPrime() outside of the conditional.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter