Course Content
C++ Introduction
C++ Introduction
A Little Math
These five mathematical operators (+
, -
, *
, /
, and %
) serve to carry out various mathematical operations:
main
#include<iostream> int main() { int myVar = 9; int yourVar = 5; //using the sum operator (+) int resultSum = myVar + yourVar; std::cout << "9 + 5 = " << resultSum << std::endl; //using the subtraction operator (-) int resultDiff = yourVar - myVar; std::cout << "5 - 9 = " << resultDiff << std::endl; //using the multiplication operator(*) int resultMult = myVar * yourVar; std::cout << "9 * 5 = " << resultMult << std::endl; //using the division operator (/) int resultDiv = myVar / yourVar; std::cout << "9 / 5 = " << resultDiv << std::endl; //using the modulo operator (%) int resultModDiv = myVar % yourVar; std::cout << "9 % 5 = " << resultModDiv << std::endl; }
The modulo operator (%
) calculates and returns the remainder resulting from a standard division operation.
The division operator (/
) returns only the integer part of the result, discarding any remainder. For instance, when dividing 10 by 3, the result is 3, not 3.333... To obtain the desired division result with decimals (e.g., 10 / 3 = 3.333), it is necessary for at least one of the operands to be of a double
or float
data type.
main
#include<iostream> int main() { // one of the variable must be double or float type double myVar = 9; int yourVar = 5; std::cout << "9 / 5 = " << myVar / yourVar << " (Expected result)" << std::endl; // both operands of integer type int myVar1 = 9; int yourVar1 = 5; std::cout << "9 / 5 = " << myVar1 / yourVar1 << " (Not the expected result)" << std::endl; }
The sum operator is the only mathematical operator that can be applied to string (that called concatenation):
main
#include<iostream> #include<string> int main() { std::string myVar = "code"; std::string yourVar = "finity"; //using sum operator (+) for concatenation std::string resultSum = myVar + yourVar; std::cout << "code + finity = " << resultSum << std::endl; }
There are also comparison operators (>
, <
, <=
, >=
). They are utilized when you need to numerically compare a value to a specific range:
main
#include<iostream> int main() { int myVar = 9; int yourVar = 5; bool greater = (myVar > yourVar); std::cout << "9 > 5 is " << greater << std::endl; bool greaterOrEqual = (myVar >= myVar); std::cout << "9 >= 9 is " << greaterOrEqual << std::endl; bool lessOrEqual = (myVar <= yourVar); std::cout << "9 <= 5 is " << lessOrEqual << std::endl; bool less = (myVar < yourVar); std::cout << "9 < 5 is " << less << std::endl; }
Thanks for your feedback!