Exercise 12

This commit is contained in:
2025-05-23 20:07:12 +02:00
parent fec3fd845f
commit b69c732ab8
4 changed files with 303 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
#+tilte: Task 2a: Understanding Pointers - Num_Elements
#+author: JirR02
* 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
#+BEGIN_src shell
10 3 10
#+END_src
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
#+BEGIN_src cpp
#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; }
#+END_src
--------------
Made by JirR02 in Switzerland 🇨🇭