Hello, I am having some trouble with arrays. We just recently started learning them in my c++ class and I am having trouble with the assignment. Basically, I am trying to figure out how to ask the user how many times they would like to randomly generate a number and then the program should take those randomly generated numbers and put them into an array. After that is finished I need to be able to output that array showing the randomly generated numbers that were put into the array.
If any of you have any help to offer I would greatly appreciate it.
I will input some code that I was working on.
Just note that I am "coding in the dark" In other words, throwing out different attempts to try and understand it, so please do not criticize too critically as it really means nothing. It is just to show where I am at.
Line 11: You've defined an array of size 0, say with no elements. When defining the array you've to take care about the number of elements being enough to fit the users requested inputNum.
Line 19: You'll never assign any value to the array elements.
Line 21: Due to the fact, that your array doesn't contain not even one element, reading one from it would result in some undefined value (which indeed may look like a randomly created one).
#include <iostream>
#include <cstdio> // some of your header files you didn't need
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main() {
int inputNum;
int i = 0;
cout << "How many numbers would you like to randomly generate?" << endl;
cin >> inputNum;
int randomArray[inputNum]; // You have to declare the SIZE of the array.
srand (time(NULL)); //Initializes random number.
for (i = 0; i < inputNum; i++) {
randomArray[i] = rand() % 100 + 1; /* intialize all of your random numbers in your array. */
}
// Display the result
/* array[i] doesn't display anything seeing that it has no elements and outputting an array like cout << array[0] only outputs one element. */
for (int j = 0; j < inputNum; j++) {
cout << randomArray[j] << " ";
}
return 0;
}
Sorry for the late reply. Thank you guys so much for the help. I am going to restart using what you guys told me. I am understanding it much more than I did previously.