Last Updated:

C++. Using Pointers as Function Arguments

In C++, pointers can be used as arguments to functions. So, if an array acts as a parameter of a function, then a pointer to its first element is passed to the function. This is an automatic transfer of the array to the function using its address. As a result, the functions called can change the values of the elements in the original arrays and return them to the main function. Information about the number of elements in the array must be passed through a separate parameter.

Task

From the array of integers, remove all prime numbers whose value is less than the arithmetic mean of the elements of the array. The resulting array is ordered in ascending order.

Decision

It is clear that the algorithm for solving this problem without using the function will be very cumbersome. Let's break the task into subtasks:

  • calculation of the arithmetic mean of the elements of the array;
  • define a prime number;
  • Remove an element from an array.
  • order an array;

Prototype functions that are designed to solve subtasks may look like this:

  • float sr_arifm(int *x, int n) — calculates the arithmetic mean of the array x of n elements (fig. below)
  • bool prostoe(int n) — checks whether the integer n is prime, the result is a Boolean value of true if the number is prime, and false otherwise (figure below);
  • void udal(int *x, int m, int*n) — removes the element with the number m in the array x from n elements (fig. below)

 

  • void upor(int *x, int N, bool pr=true) — sorts the x array of n elements in ascending or descending order, the sort direction depends on the value of the pr parameter, if pr=true, then sorting is performed in ascending order, otherwise in descending order.

Here's what the program text will look like: