C++ and Mathematics
Variables, types and arithmetic
Structure of a C++ program, int and double, integer division and remainder, operator precedence, type conversion.
45 min 8 questions
01A first program
A C++ program starts in the main function. cout prints, and the << operator chains several values. Every variable has a type: int — integer, double — real number, bool — true/false (printed as 1/0), char — a character.
#include <iostream>
using namespace std;
int main() {
int a = 7, b = 2;
double r = 3.5;
cout << a + b << " " << a * r << "\n"; // 9 24.5
return 0;
}02Integer division and remainder
If both operands are integers, / returns the integer part (truncated toward zero): 7 / 2 is 3, -7 / 2 is -3. % returns the remainder: 7 % 2 = 1, and -7 % 2 = -1 (the remainder takes the sign of the dividend). Mathematically .
One double operand is enough for real division: 7 / 2.0 = 3.5. Careful: double x = 7 / 2; still stores 3, because the integer division happens first.
03Precedence, assignment and conversion
*, /, % are evaluated before + and -; operators of equal precedence go left to right. x += 3 means x = x + 3. i++ returns the old value and then increments; ++i increments first.
(int)3.99 or static_cast<int>(3.99) drops the fractional part (toward zero): 3, and (int)-2.5 is -2.
Key formulas
Division with remainder
intvsdouble
Worked examples
Example 1
What does this program print? It splits a number into digits.
int n = 4729;
cout << n % 10 << " " << n / 10 % 10 << " " << n / 1000;What does this code print?
#include <iostream>
using namespace std;
int main() {
cout << 17 / 5 << " " << 17 % 5;
}Sample content: questions and lessons are illustrative and are not taken from official exams.
