In C++ there are the usual arithmetic operators as in most other programming languages, namely addition, subtraction, multiplication, division and the remainder operator (modulo). In addition, there are the one-digit operators for positive and negative sign.
| Operator | Description |
|---|---|
| + | Addition / sign |
| – | Subtraction / sign |
| * | Multiplication |
| / | Division |
| % | Rest (modulo) |
#include <iostream>
#include <iomanip> // Library for specifying the decimal places
using namespace std;
int main() {
int a = 4, b = 6;
long c = 7;
double z = 0;
cout << "Starting values" << endl;
cout << "a = " << a << "\nb = " << b << "\nc = " << c << endl;
cout << "Calculations" << endl;
z = (double)a / (double)b;
// setprecision() = Funktion from library <iomanip>,
// for specifying the decimal places
cout << "z = a / b = " << setprecision(2) << z << endl;
if (a % 2 == 0) {
cout << "Number " << a << " = even" << endl;
} else {
cout << "Number " << a << " = odd" << endl;
}
}
Starting values
a = 4
b = 6
c = 7
Calculations
z = a / b = 0.67
Number 4 = even
iostream and iomanip. iostream provides input and output functionality, while iomanip allows specifying the decimal places.main() function, several variables are declared and initialized:
a is an int variable initialized with the value 4.b is an int variable initialized with the value 6.c is a long variable initialized with the value 7.z is a double variable initialized with the value 0.cout statements are used to display information on the console. They use the << operator to insert values and strings into the output stream.cout << "Starting values" << endl; outputs the string “Starting values” followed by a newline character.cout statement displays the values of variables a, b, and c using the << operator. Each value is inserted into the output stream.cout << "Calculations" << endl; outputs the string “Calculations” followed by a newline character.z = (double)a / (double)b; performs a calculation and assigns the result to the variable z. The (double) type casting is used to ensure that the division is performed with floating-point arithmetic.cout << "z = a / b = " << setprecision(2) << z << endl; displays the value of z with a precision of 2 decimal places using the setprecision() function from the iomanip library. The setprecision() function modifies the behavior of the << operator.if statement is used to perform a conditional check. It checks if the value of a is even or odd.a % 2 == 0 is true (meaning a is divisible by 2 with no remainder), the code block inside the if statement is executed. It outputs the string “Number a = even” where a is the value of the variable.a % 2 == 0 is false (meaning a is not divisible by 2 with no remainder), the code block inside the else statement is executed. It outputs the string “Number a = odd” where a is the value of the variable.