Answer to Question #346503 in C++ for aimen

Question #346503

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.


1
Expert's answer
2022-05-30T15:05:27-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS