Arrays

My program below is suppose to generate 10 random numbers ranging from 0-9 ,
and tally them up in index order, for example if i get three 0's, it should print the index 0 with a value of 3 , all the way up until the 9nth index, but the way i have it set up it seems to only be replacing the 0's with a 1 and thats it, where am i going wrong? thanks in advance.
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
#include<iostream>
using namespace std;

int main() {


const int LENGTH = 10;
int tallyArray[LENGTH]{0,0,0,0,0,0,0,0,0,0}; // all elements 0

    srand(time(0));

for ( int i = 0; i <LENGTH;i++) {

    int randNumber = rand() % 9;

    if (tallyArray[i] == randNumber)
    tallyArray[i]+=1;

    cout << randNumber << "\n";

}

for (int i = 0; i < LENGTH; i++){
    cout << tallyArray[i] << "\n";

}

    return 0;
}
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>

using namespace std;

int main() {
    
    
    const int LENGTH = 10;
    int tallyArray[LENGTH]{0}; // all elements 0
    
    srand(time(NULL));
    
    for ( int i = 0; i <LENGTH;i++) {
        
        int randNumber = rand() % 9;
        tallyArray[randNumber]++;
    }
    
    for ( int i = 0; i <LENGTH;i++) {
        cout << i << ':' << tallyArray[i] << '\n';
    }
    return 0;
}



0:0
1:2
2:1
3:3
4:1
5:0
6:1
7:2
8:0
9:0
Program ended with exit code: 0
Last edited on
wow such a simple fix , thank you very much
Topic archived. No new replies allowed.