I've been currently stuck on a C++ problem for about an hour and half. Here's the question:
Write a program that generates one hundred random integers between 0 and 9 and displays the count for each number. (Hint: Use rand()
% 10 to generate a random integer between 0 and 9. Use an array of ten integers,
say counts, to store the counts for the number of O's, l 's, . .. , 9's.)
And here's what I have so far. I think I'm pretty close, but I keep on getting "0" for the occurrences (or counts) of each random integer. Any help would be greatly appreciated.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>
#include <fstream>
usingnamespace std;
constint SIZE = 100;
int main()
{
int integers[SIZE];
int index;
int zero = 0;
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
cout << "The following 100 integers are random:" << endl;
cout << endl;
srand(time(0));
for (index = 0; index < SIZE; index++)
{
integers[SIZE] = rand() % 10;
cout << integers[SIZE] << " ";
}
cout << endl;
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 0)
{
zero += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 1)
{
one += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 2)
{
two += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 3)
{
three += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 4)
{
four += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 5)
{
five += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 6)
{
six += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 7)
{
seven += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 8)
{
eight += 1;
}
}
for (index = 0; index < SIZE; index++)
{
if (integers[index] == 9)
{
nine += 1;
}
}
cout << "The number of zeros in the random list are " << zero << endl;
cout << "The number of ones in the random list are " << one << endl;
cout << "The number of twos in the random list are " << two << endl;
cout << "The number of threes in the random list are " << three << endl;
cout << "The number of fours in the random list are " << four << endl;
cout << "The number of fives in the random list are " << five << endl;
cout << "The number of sixes in the random list are " << six << endl;
cout << "The number of sevens in the random list are " << seven << endl;
cout << "The number of eights in the random list are " << eight << endl;
cout << "The number of nines in the random list are " << nine << endl;
getch();
return 0;
}
Let me suggest that when you having a tonne of if statements often means your code is doing something repetitive that you should code differently (with fewer lines).