liveBook · Manning

Even number

As explained in Learn C++ by Example

An even number is an integer divisible by two without a remainder.

An even number is an integer divisible by two without a remainder. In C++, test parity with i % 2: a zero result marks an even number. section 9.1.4

Use the parity test to classify values:

  • Return '*' when i % 2 is zero, identifying an even number. section 9.1.4
  • Return '.' when i % 2 is nonzero, identifying an odd number. section 9.1.4

Triangle-number parity

The first triangle numbers are 1, 3, 6, and 10. Their parity markers are '.', '.', '*', and '*'. Applying the transformation to the first 20 values produces a repeating marker sequence. section 9.1.4

Listing 9.5 Checking whether the numbers are odd or even
#include <algorithm>
#include <iostream>
#include <iterator>
 
void demo_further_properties()
{
    const int count = 20;
    const auto triangle_numbers = make_triangle_numbers(count);
    std::vector<char> odd_or_even;                       #1
    std::ranges::transform(triangle_numbers,
        std::back_inserter(odd_or_even),
        [](int i) { return i % 2 ? '.' : '*'; });        #2
    std::ranges::copy(odd_or_even,
        std::ostream_iterator<char>(std::cout, " "));    #3
    std::cout << '\n';
}

Inspect a complete C++ function that transforms triangle numbers into odd/even markers and copies them to standard output. section 9.1.4

How Learn C++ by Example covers it

How deep it goes
Checks parity through modulo arithmetic and applies the result with a lambda, stopping short of deeper number theory.
Examples
Uses the first triangle numbers and a twenty-value marker sequence containing dots for odd and asterisks for even.
What it assumes
Assumes integer sequences, modulo arithmetic, lambdas, vectors, and basic C++ ranges usage.
What you can do after
Apply it via modulo arithmetic and std::ranges::transform to label values as odd or even.
How it connects
Connects even numbers with odd numbers, parity, modulo arithmetic, triangle numbers, lambda expressions, and std::ranges::transform.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.