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

C++ and Mathematics

Conditions and loops

if/else, logical operators, for and while loops, sums Σ\Sigma and products in code, nested loops.

50 min 8 questions

01Conditions

if (condition) { ... } else { ... }. Comparisons: ==, !=, <, <=, >, >=; logic: && (and), || (or), ! (not). A classic bug: = assigns, == compares.

Divisibility is checked with the remainder: n % d == 0 means d∣nd \mid n.

02Loops and sums

A sum ∑i=1nf(i)\sum_{i=1}^{n} f(i) is a loop in code: start with s = 0 (p = 1 for a product!) and add one term per step. for (int i = 1; i <= n; i++) visits 1,2,…,n1, 2, \ldots, n.

while (condition) repeats as long as the condition is true — useful when the number of iterations is not known in advance (e.g. "how many times must we multiply by 3 to exceed 100?").

C++
int s = 0;
for (int i = 1; i <= n; i++) {
    s += i;            // s = 1 + 2 + ... + n = n(n+1)/2
}

03Nested loops

A loop inside a loop: the inner loop runs completely for every step of the outer one. If the outer runs nn times and the inner mm times, there are nmnm iterations. If the inner loop starts at j = i, the count is n+(n−1)+⋯+1=n(n+1)2n + (n - 1) + \dots + 1 = \frac{n(n+1)}{2}.

Key formulas

  • Sum formulas (to check your loops)

    ∑i=1ni=n(n+1)2,∑i=1ni2=n(n+1)(2n+1)6\sum_{i=1}^n i=\dfrac{n(n+1)}2,\qquad \sum_{i=1}^n i^2=\dfrac{n(n+1)(2n+1)}6
  • Geometric sum

    ∑k=1n12k=1−12n\sum_{k=1}^n\dfrac1{2^k}=1-\dfrac1{2^n}

Worked examples

Example 1

Write a program counting the numbers from 1 to 100 divisible by 3 or 5.

C++
int c = 0;
for (int i = 1; i <= 100; i++)
    if (i % 3 == 0 || i % 5 == 0) c++;
cout << c;   // 47