Cpp Boolean Expressions - Learn C++ Programming

Today, we will learn Data type bool and C++ Boolean Expressions with examples and will discuss how it works and usage of bool variables.

C++ Booleans

Sometimes, You have to need a data type that can return one of two values in programming, like

  • YES / NO
  • ON / OFF
  • TRUE / FALSE


In C++, We will use the bool data type. which can take the values true(1) or false(0)

Boolean Values

A boolean variable will be declared with the bool keyword and return the value true or false. the example below

So, see the Example:

#include <iostream>
using namespace std;

int main()
{
     bool isCodingFun = true;
     bool codingIsBad = false;
     cout << isCodingFun  << endl;
     cout << codingIsBad;
        return 0;
}

Output:

1
0

So, we use true for displaying 1 and false use for displaying 0, In the next chapters, we will use this in condition checking and loops and many more

C++ Boolean Expressions

So, gays, Now we are discussing Boolean Expressions that they return a boolean value 1 (true) or 0 (false), and here will talk a little bit about conditions.

You can use a comparison operator, as a greater than (>) operator. Because its a part of conditions to find out if an expression or a value is true

So, Example 1:

#include <iostream>
using namespace std;

int main()
{
     int x = 15;
     int y = 9;
     cout << (x > y);
        return 0;
}

its output will be 1. Because value of x’s is bigger from y. Now i am explaining you more examples with different use of boolean.

Example 2:

#include <iostream>
using namespace std;

int main()
{
     cout << (15 > 9);
        return 0;
}

In this example, you can use direct values in condition. Butt Answer will be the same. So its a meter of style.

Example 3:

#include <iostream>
using namespace std;

int main()
{
     int xVal = 20;
     cout << (xVal == 20);
        return 0;
}

So, in this example 3, you will learn the use of a double equal sign operator with boolean. the Answer will tell you that xVal is equal to 20 or not, So the Answer is 1. Because the condition is true.

Example 4:

#include <iostream>
using namespace std;

int main()
{
     cout << (15 == 20);
        return 0;
}

In example 4, we check direct values that they are equal or not. So the value 1 is 15 and value 2 is 20. the both values are not same, in this way the condition will be false. So, it will return 0 (false).

Today we are covered these topics C++ boolean and its Expressions.

I hope you enjoy this course on this platform TCMaster.co. Now Go to Checkout Our Recent Chapters of C++

By Usama Arshad

It's me Usama Arshad working as a Lecturer C++. I am a student of BSIT.

Leave a Reply

Your email address will not be published. Required fields are marked *