Write a C++ program.
Dynamically allocate a 1D integer array of size n. Populate it with random numbers from 1 to
99.
Display the array in main function. Pass it to a void function difference() along with a variable
‘diff’ by reference.
The function displays the highest and the lowest element in the array and calculates the
difference between the highest and the lowest element and return it to the main function using
the variable passed where it is displayed.
#include <iostream>
#include <ctime>
void difference(int* arr, int size, int* diff);
int main()
{
std::srand(std::time(nullptr));
std::cout << "Enter size of array: ";
int size{0};
std::cin >> size;
int* arr = new int[size];
for(int i = 0; i < size; ++i)
{
*(arr + i) = rand() % 99 + 1;
std::cout << *(arr + i) << " ";
}
std::cout << std::endl;
int diff = 0;
difference(arr, size, &diff);
std::cout << "Difference: " << diff << std::endl;
}
void difference(int* arr, int size, int* diff)
{
int minValue = 99;
int maxValue = 1;
for (int i = 0; i < size; ++i)
{
if (*(arr + i) > maxValue)
maxValue = *(arr + i);
if (*(arr + i) < minValue)
minValue = *(arr + i);
}
std::cout << "Highest element: " << maxValue << std::endl;
std::cout << "Lowest element: " << minValue << std::endl;
*diff = maxValue - minValue;
}
Comments
Leave a comment