C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. This tutorial aims to introduce beginners to the basic concepts of operators and expressions in C++.
What you will learn:
Prerequisites:
Operators in C++ are symbols that tell the compiler to perform specific mathematical or logical functions. C++ has several types of operators:
An expression in C++ is a combination of operators, constants, and variables that yield a result value. For example, a simple arithmetic expression 5 + 3
yields the result 8
.
Here are some examples to demonstrate the operators and expressions in C++:
Example 1: Arithmetic Operators
#include<iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
cout << "a + b = " << a + b << endl; // Adds a and b
cout << "a - b = " << a - b << endl; // Subtracts b from a
cout << "a * b = " << a * b << endl; // Multiplies a and b
cout << "b / a = " << b / a << endl; // Divides b by a
cout << "b % a = " << b % a << endl; // Modulus operator, returns the remainder of b divided by a
return 0;
}
When you run the program, the output will be:
a + b = 30
a - b = -10
a * b = 200
b / a = 2
b % a = 0
Example 2: Logical Operators
#include<iostream>
using namespace std;
int main() {
bool a = true; // Boolean variable a with value true
bool b = false; // Boolean variable b with value false
cout << "(a && b) = " << (a&&b) << endl; // Logical AND operator. If both operands are non-zero, then the condition becomes true.
cout << "(a || b) = " << (a||b) << endl; // Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
cout << "(!a) = " << (!a) << endl; // Logical NOT Operator. It is used to reverse the logical state of its operand.
return 0;
}
When you run the program, the output will be:
(a && b) = 0
(a || b) = 1
(!a) = 0
In this tutorial, we have learned about different types of operators in C++, such as arithmetic, logical, and assignment operators. We also learned how to use these operators in C++ expressions.
Next steps for learning:
Additional Resources:
Solutions with explanations:
Bitwise Operators: The bitwise operators perform operations on the binary representations of numbers. The AND operator (&) returns 1 if both bits are 1, the OR operator (|) returns 1 if either bit is 1, the XOR operator (^) returns 1 if the bits are different, and the NOT operator (~) flips the bits.
Ternary Operator: The ternary operator (?:) is a shorthand for an if-else statement. It has the form condition ? expression_if_true : expression_if_false
.
Assignment Operators: The assignment operators are used to assign a new value to a variable. The basic assignment operator is =, but there are also compound assignment operators like +=, -=, *=, and /= which combine an operation with assignment. For example, a += b
is equivalent to a = a + b
.