JirR02 99962171df Exercise 12
Added Exercise 12 to Repo
2025-05-23 22:56:38 +02:00
..
2025-05-23 22:56:38 +02:00

Task Description

Complete the definition of function num_elements by editing the file num_elements.cpp according to its specified pre- and post conditions.

We provide a test program using the implemented function to find the number of elements in a specified interval of a vector.

Input

The test program accepts

  • a vector length,
  • the start index a, and
  • the end index b.

For example

10 3 10

means a 10-element vector and the interval between index 3 and 9.

Output

The test program prints the number of elements in the interval [a,b).

For example the input given above, this value is 7.

Solution

#include "num_elements.h"
#include <iostream>

// PRE: a <= b are valid pointers to elements of the same contiguous memory
// block. POST: Returns the number of elements in between those pointers
// (starting at a, not including b).
int num_elements(const int *a, const int *b) { return b - a; }

Made by JirR02 in Switzerland 🇨🇭