Skip to content
The site is in test mode. All features are free for now.
MathAgora

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.

C++
#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 a=(a/b)⋅b+a%ba = (a / b)\cdot b + a \% b.

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

    a=⌊ab⌋b+(a mod b)(a,b>0)a=\left\lfloor\tfrac ab\right\rfloor b+(a\bmod b)\quad(a,b>0)
  • int vs double

    7/2=3,7%2=1,7/2.0=3.57/2=3,\quad 7\%2=1,\quad 7/2.0=3.5

Worked examples

Example 1

What does this program print? It splits a number into digits.

C++
int n = 4729;
cout << n % 10 << " " << n / 10 % 10 << " " << n / 1000;