C ++ Biggest number checker
Hi guys, I was tasked with creating a program that creates n arrays of 10 random numbers. The program should add all integers and display the result. After that, it should check which of the sum is the largest and it should display this array and the result. I'm having trouble with this and would like some help! Thanks again. Here is my code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double random(unsigned int &seed);
unsigned int seed = 5;
void generateData(int set[10]);
int sumData(int set[10]);
void checkData(int sumResult, int arrayNumber);
int main (int argc, char * const argv[]) {
int arrayNumber, sumResult;
int set[10];
do {
cout << "Number of Arrays to Compare: " << endl;
cin >> arrayNumber;
} while (arrayNumber < 0);
for (int i = 0; i < arrayNumber; ++i) {
generateData(set);
sumResult = sumData(set);
cout << "Sum --> " << sumResult << endl;
checkData(sumResult, arrayNumber);
}
return 0;
}
double random(unsigned int &seed) {
const int MODULUS = 15749;
const int MULTIPLIER = 69069;
const int INCREMENT = 1;
seed = ((MULTIPLIER * seed) + INCREMENT) % MODULUS;
return double(seed) / double(MODULUS);
}
void generateData(int set[10]) {
for (int i = 0; i < 10; ++i) {
set[i] = int (5 + 6 * random(seed));
cout << set[i] << " || ";
}
}
int sumData(int set[10]) {
int sumTotal = 0;
for (int i = 0; i < 10; ++i)
sumTotal = sumTotal + set[i];
return sumTotal;
}
void checkData(int sumResult, int arrayNumber) {
int largerNumber;
int tempSet[2];
for (int i = 0; i < arrayNumber; ++i) {
if (sumResult > largerNumber) {
tempSet[i] = sumResult;
}
}
}
+2
a source to share
3 answers
Your question reads
create a program that creates n arrays of 10 random numbers ....
- But I only see one
int
size array10
. What you have to do is allocate a 2D array sizearrayNumber X 10
, name itset
. - Also you should allocate a 1D array of size
arrayNumber
called saysumArray
, to hold the sum of each array. sosumArray[i]
will be the sum of all the elements of the arrayith
inset
. - Then you will find the max element and its index (say
maxIndex
) atsumArray
- Print the array at index
maxIndex
inset
, which will be the array having the maximum sum.
+2
a source to share
To create arrays of arrays of ints, a simple way is as follows:
int **createArrayOfArrays(int number, int lengthOfEach)
{
int **array_of_arrays = (int**) malloc(sizeof(int*) * number);
int ix;
for(ix = 0; ix < number; ix++)
{
array_of_arrays[ix] = (int*) malloc(sizeof(int) * lengthOfEach);
}
return array_of_arrays;
}
Don't forget to free all memory at the end, you need to free every array and array of arrays (one free per malloc).
0
a source to share