132k views
15 votes
Write a code in C++ that can save 100 random numbers in an array that are between 500 and 1000. You have to find the average of the 100 random numbers. To find the average of the numbers, you have to use a functions. You are not allowed to use return, cin or cout statements in the functions.

Hint : you have to use function call by reference.

User Vedrano
by
3.3k points

1 Answer

4 votes

Answer:

#include <iostream>

#include <random>

//here we are passing our array and a int by ref

//to our function called calculateAverage

//void is infront because we are not returning anything back

void calculateAverage(int (&ar)[100], int &average){

int sum = 0;

for(int i = 0;i < 100; i++){

//adding sum

sum += ar[i];

}

//std:: cout << "\\average \t\t" << average;

//calculating average here

average += sum/100;

}

int main() {

int value = 0;

int average = 0;//need this to calculate the average

int ar[100];

//assign random numbers from 500 to 1000

//to our array thats called ar

for(int i = 0; i < 100; i++){

value = rand() % 500 + 500;

ar[i] = value;

}

calculateAverage(ar,average);

// std:: cout << "\\average should be \t" << average;

}

Step-by-step explanation:

not sure how else this would work without having to pass another variable into the function but I hope this helps!

I commented out the couts because you cant use them according to ur prof but I encourage you to cout to make sure it does indeed calculate the average!

User Amir Tugi
by
3.1k points