For my C++ book (C++ without fear) I made this program for a random number generator and an array. It tells you how many times a number between 0 and 9 is picked and then tells the accuracy. I have the program set up where you can test multiple times and then quit by pressing 0. For this to work you need a for loop in the beggining that initalizes all elements of the array to 0.
for (i = 0; i < n; i++)
{
r = rand_0toN1(VALUES);
hits [r] = 0;
}
I was wondering how I could make a function that has that loop and returns all elements of the array being 0. I have slight confusion on functions sometimes. Although I already have the program working I just want to incorporate that for loop into a function so I can get better at them. I am completley stumped though so any feedback would be nice.
Here is my full program if interested.
//stats.cpp using #define VALUES
#include <iostream>
#include <ctime>
#include <cmath>
usingnamespace std;
#define VALUES 10
int rand_0toN1(int n);
int hits [VALUES];
int i, n, r;
int main () {
//Number of trials; prompt from user
//All purpose loop variable
//Holds a random value
srand(time(NULL)); //Set seed for randomizing
while (true)
{
cout << "Enter how many trials (0 is exit) and press ENTER: ";
cin >> n;
if (n == 0)
break;
for (i = 0; i < n; i++)
{
r = rand_0toN1(VALUES);
hits [r] = 0;
}
//Run n trials. For each trial, get a num 0 to 9 and then increment the corresponding element in the hits array.
for (i = 0; i < n; i++)
{
r = rand_0toN1(VALUES);
hits [r]++;
}
//Print all elements in the hits array along with ratio of hits to EXPECTED hits (n / 10)
for (i = 0; i < VALUES; i++)
{
cout << i << ": " << hits [i] << " Accuracy: ";
double results = hits[i];
cout << results / (n / VALUES) << endl;
}
}
}
int rand_0toN1(int n){
return rand() % n;
}
I'm not sure if this is what you exactly want but as I understood on the program start you want every value stored in the array to be set to 0.
You can do this by doing this
1 2 3 4
for (i = 0; i < n; i++)
{
hits[i]=0; // what it does is it sets every element[i] of the array to 0
}
I'm not sure if this is what you exactly are looking for.
Good Luck
~W0ot