Hello,
I'm learning about arrays in c++ and have two questions. I have created this program that's randomizing numbers between 1-100, but somehow the last output number is always 0. And the second thing, now the output is just one long column with one empty line between each number(as I want) but what if I want to change it so all the 1:s is on one row, all the 2:s is on one row etc...
In C++ (but not in fortran) array indexing starts at 0. So the elements of x[] are
x[0], x[1], x[2], ... , x[299]
Both your for() loops need to be aware of this. On line 19 you should have idx=0 as initial value, not 1. On line 23 you should have 0 as initial value and use <num, not <=num.
If you want to have all the occurrences of a particular digit on one line then you will have to set up another array to count them.
As lastchance said, you need an array to count the occurrences.
1 2 3 4 5 6 7 8 9 10
constint MAX_RAND = 100;
int count[MAX_RAND+1] = {0}; // Here we ignore [0] and use [1]-[100] because of your rand() function.
...
// Replace lines 19-20;
int r;
for(size_t idx=0; idx < num; idx++)
{ r = rand() % MAX_RAND + 1;
x[idx] = r;
count[r]++;
}
I've limited the range of your random numbers to 0 - (RANGE-1), that is 0 - 9 by default below. Otherwise you will end up with an excessive proportion of blank lines.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
constint SIZE = 300;
constint RANGE = 10; // Limited range of random numbers to 0 - (RANGE-1)
int x[SIZE];
int count[RANGE] = { 0 }; // Initialises rest to zero, because I didn't specify all the initial values
int numRandom;
int r;
int i, j;
cout << " How many integers do you want to randomize ( <= " << SIZE << ": "; cin >> numRandom;
// Generate some random numbers
srand( time(NULL ) );
for( i = 0; i < numRandom; i++ )
{
r = rand() % RANGE; // Changed to a random number between 0 and RANGE-1 inclusive (for convenience)
x[i] = r; // Store the random number (assuming that you really want to)
count[r]++; // Add to count for this value
}
cout << "\nThe original random numbers are:\n";
for( i = 0; i < numRandom; i++ ) cout << x[i] << " ";
cout << "\n\nThe random numbers in order are:\n";
for ( j = 0; j < RANGE; j++ )
{
for ( i = 0; i < count[j]; i++ ) cout << j << " ";
cout << endl;
}
cout << "\nThe random numbers by count are:\n";
for ( j = 0; j < RANGE; j++ ) cout << j << ": " << count[j] << endl;
}