so i am supposed to have a program that creates random numbers between 1 and 10, assign the numbers to an array and then give the sum of all numbers. My question is why am i getting weird numbers?
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
#include <ctime>
using std::time;
#include <cstdlib>
using std::rand;
using std::srand;
void randArray( int[], int );
void sumArray( int[], int );
int main()
{
const int arraySize = 10; // constant array size
int a[ arraySize ] = {0}; //setting array a to all 0's
for ( int i = 0; i < arraySize; i++ )
cout << a[i] << endl;
randArray(a, arraySize); //passing array a to randArray by reference
sumArray(a, arraySize); //passing array a to sumArray by reference
return 0;
}
//creates 10(based on arraysize from main) random numbers from 1 to 10
void randArray( int b[], int size ) //points to original array a
{
srand( time (0));
for ( int roll = 0; roll < size; roll++ )
cout << "randon numbers are: " << b[ 1 + rand() % 10 ]++ << endl;
}
//creates to total sum of array a
void sumArray ( int c[], int secSize )
{
int total = 0;
for ( int sum = 0l; sum < secSize; sum++ )
total += c[sum];
cout << "Total of all random numbers is: " << total << endl;
}
output looks like this:
random numbers are: 0
random numbers are: 0
random numbers are: 0
random numbers are: 0
random numbers are: -858993460
random numbers are: 1
random numbers are: 0
random numbers are: 1
random numbers are: 0
random numbers are: 2
Total of all random numbers is: 9
I get this over and over again with different numbers. Sometimes I get numbers like -858993460 a few times and an error that says:
run time check failure #2 - stack around the variable 'a' was corrupted.
I see that I had the wrong number for arraySize, it should have been 11 instead of 10. After changing that I no longer get negative numbers but now all I get are 0, 1, and 2.