➕ C++ Math & Booleans

Soumik DastidarSoumik Dastidar
3 min read

🔢 Math in C++

C++ supports all basic arithmetic operations:

OperatorMeaningExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division5 / 22 (int division)
%Modulus (remainder)5 % 21

⚠️ If you divide two integers, the result will also be an integer. Use float or double for decimal precision.

🧠 Example:

int a = 10, b = 3;
cout << "Sum: " << a + b << endl;
cout << "Quotient: " << (float)a / b << endl;

🧮 Math Functions

To access advanced mathematical operations, include the <cmath> library:

#include <cmath>

🧰 Useful Functions

FunctionDescriptionExampleResult
sqrt(x)Square rootsqrt(16)4
pow(x, y)Powerpow(2, 3)8
round(x)Rounds to nearest intround(3.6)4
floor(x)Rounds downfloor(3.9)3
ceil(x)Rounds upceil(3.1)4
abs(x)Absolute valueabs(-5)5

🔁 Booleans in C++

A boolean (or bool) stores one of two values:

  • true (1)

  • false (0)

✅ Declaration and Use

bool isOnline = true;
cout << isOnline;  // Output: 1

Booleans are mostly used in conditions, loops, and comparisons.

🔍 Comparison Operators

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater or equal5 >= 5true
<=Less or equal3 <= 5true

🧠 Logical Operators

OperatorMeaningExampleResult
&&AND (both true)true && falsefalse
``OR (either true)
!NOT (opposite)!truefalse

🧪 Example Code

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int a = 9;
    float result = sqrt(a);
    cout << "Square root of " << a << " is " << result << endl;

    bool isEven = (a % 2 == 0);
    cout << "Is " << a << " even? " << isEven << endl;
    return 0;
}

🖨️ Sample Output:

Square root of 9 is 3
Is 9 even? 0

💼 Task for You

🔧 Task:

  1. Take two numbers as input.

  2. Output their sum, product, and power (a^b).

  3. Check if both numbers even use Boolean logic.

  4. Print true/false results accordingly.

💡 Hint: Use pow() and (num % 2 == 0).

🎯 What’s Next?

With math and logic covered, you’re ready to control the flow of your programs! In the next part, we’ll cover Conditional Statements (if, else, switch) — the heart of decision-making in programming.

📍Next up: Part 8 – Conditional Statements in C++

✨ Follow the Series

This post is part of the C++ Zero to Hero blog series — your roadmap to learning C++ from the ground up. Stay consistent, code along, and you’ll get there!

0
Subscribe to my newsletter

Read articles from Soumik Dastidar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Soumik Dastidar
Soumik Dastidar

I'm Soumik—a passionate problem solver, aspiring software developer, and lifelong learner. Currently building a C++ Complete Series to help beginners master programming from scratch. I love breaking down complex concepts, automating real-world tasks, and sharing what I learn. Let's grow together, one line of code at a time.