Design and implement a c++ program which, when executed by the computer, fills an array with randomly generated integer values between Min_Value and Max Value, which are constants. The array should hold n values, where n is a constant. The computer should then output the contents of the array and sum of array element values. Write and invoke a function to sum the elements in the array in the main function.
#include <iostream>
#include <cstdlib>
#include <ctime>
constint MinValue = 0;
constint MaxValue = 10;
constint ARRAY_SIZE = 5;
// generates a random value
int generateValue()
{
// set seed value
// produce integers between Min and Max values
int randValue = std::rand() % (MinValue + MaxValue);
return randValue;
}
// computes the sum of elements in the array
int sum(int *ptrArray, int size){
int sum = 0;
for(int i = 0; i < size; i++){
sum += ptrArray[i];
}
return sum;
}
int main(){
int array[ARRAY_SIZE];
for(int i = 0; i < ARRAY_SIZE; i++)
{
array[i] = generateValue();
std::cout << "array[" << i << "] = "
<< array[i] << std::endl;
}
std::cout << "Sum of numbers in array is " << sum(array, ARRAY_SIZE) << std::endl;
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
constint MinValue = 0;
constint MaxValue = 10;
constint ARRAY_SIZE = 5;
// generates a random value
int generateValue()
{
// set seed value
// produce integers between Min and Max values
int randValue = rand() % (MinValue + MaxValue);
return randValue;
}
// computes the sum of elements in the array
int sum(int *ptrArray, int size){
int sum = 0;
for(int i = 0; i < size; i++){
sum += ptrArray[i];
}
return sum;
}
int main(){
int array[ARRAY_SIZE];
for(int i = 0; i < ARRAY_SIZE; i++)
{
array[i] = generateValue();
cout << "array[" << i << "] = "
<< array[i] << endl;
}
cout << "Sum of numbers in array is " << sum(array, ARRAY_SIZE) << endl;
return 0;
}
I got the code to work but there was a small problem. the random number always outputs 0 as the minimum and the maximum always outputs 10 I tried coding to find the minimum and maximum of the random numbers the compiler generates but i couldn't figure out to make it work properly. this is what i have so far
I got the code to work but there was a small problem. the random number always outputs 0 as the minimum and the maximum always outputs 10 I tried coding to find the minimum and maximum of the random numbers the compiler generates but i couldn't figure out to make it work properly. this is what i have so far
I don't think you should be looking for the minimum and maximum numbers since they are supposed to be constants. Also the problem didn't say you had to look for them. But if you want to look for the maximum number in the array you could use the following
1 2 3 4 5 6 7 8 9 10 11
int findMax(int *array){
int maxInArray = array[0];
for(int i = 0; i < ARRAY_SIZE; i++){
if(maxInArray < array[i]){
maxInArray = array[i];
}
}
return maxInArray;
}