0

I started learning C++ yesterday and now I try to create a program that generate random numbers that should be stored in an array. The problem is that it store only the last number generated. This is my code (sorry if it looks awful - and probably it really is):

int num = 0;
int i = 0;
int generatedNumbers[10];

int main()
{
    srand(time(NULL));
    num = rand() % 10; 
    generatedNumbers[i] = num; 
    if (num != 0) {
        cout << num << endl;
        return choice();
    } else {
    main();
    }
}

int choice() {
   [.....USELESS STUFF....]
                cout << generatedNumbers[i] << endl;
}

So let's say the program generate the numbers: 3, 1, 8, 9. If I wanna see the numbers stored in generatedNumbers, the only number that appears is the last one (in this case, 9) and it appears four times (in this particular case). I'm pretty sure is very easy to solve the problem but honestly I kinda lost my patience. Thanks alot!

Andrew
  • 3
  • 2
  • 2
    Open the chapter in your C++ book that explains how to use a `for` loop, and read it. Calling `main()`, in this manner, is completely wrong. Read your C++ book, and use a `for` loop. – Sam Varshavchik Sep 02 '19 at 20:12
  • 1
    What ressource are you learning from? You are not allowed to call `main` and you shouldn't use global variables, probably also `rand` should be replaced by `` facilities. – walnut Sep 02 '19 at 20:14
  • Thank you guys! I will be more careful regarding calling `main` in another function and using global variables. I don't have a book to learn from, I just read some basic theory and I said to myself that it should be fun to solve some problems. That's it. – Andrew Sep 02 '19 at 20:32
  • 1
    @Andrew You should learn C++ in a structured way. It has lots of quirks and rules you need to follow, which the compiler will not warn you on if you break them. See https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – walnut Sep 02 '19 at 20:38

1 Answers1

1

Replace

num = rand() % 10; 
generatedNumbers[i] = num;

with

while (i<10) {
    num = rand() % 10; 
    generatedNumbers[i] = num;
    i = i + 1;
}

And run you program under debugger step-by step to understand what's going on.