Question about arrays.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//stats.cpp using #define VALUES
#include <iostream>
#include <ctime>
#include <cmath>
using namespace 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;
}
Last edited on
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
Last edited on
For this to work you need a for loop in the beggining that initalizes all elements of the array to 0

Not really, you've already initialized all elements of the array hits to zero by giving it static storage duration.
Topic archived. No new replies allowed.