Random
In the future steps, we will work with multiple arrays simultaneously. It can be a bit painful to fill them manually. Letβs write the program, which will fill the array with random values. To generate a random number, you can use the function rand()
:
12int a = rand(); cout << a;
Too large, isnβt it? To set restrictions on the range in which you want to get a number, use the symbol %
. For instance, the following code will print a random number less than 10:
int a = rand() % 10;
cout << a;
You can also set the start of the required range. Just add +
. The following program will write the random number in the range of 10 to 20:
int a = rand() % 20 + 10;
cout << a;
Now we know how to get the random value. Letβs fill the array with random numbers from 1 to 20!
1234for (int i = 0; i < 5; i++){ numbers[i] = rand() % 20 + 1; cout << numbers[i] << " "; }
Random is often used in game development. Letβs play!
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Ask me questions about this topic
Summarize this chapter
Show real-world examples
Awesome!
Completion rate improved to 2.94
Random
Swipe to show menu
In the future steps, we will work with multiple arrays simultaneously. It can be a bit painful to fill them manually. Letβs write the program, which will fill the array with random values. To generate a random number, you can use the function rand()
:
12int a = rand(); cout << a;
Too large, isnβt it? To set restrictions on the range in which you want to get a number, use the symbol %
. For instance, the following code will print a random number less than 10:
int a = rand() % 10;
cout << a;
You can also set the start of the required range. Just add +
. The following program will write the random number in the range of 10 to 20:
int a = rand() % 20 + 10;
cout << a;
Now we know how to get the random value. Letβs fill the array with random numbers from 1 to 20!
1234for (int i = 0; i < 5; i++){ numbers[i] = rand() % 20 + 1; cout << numbers[i] << " "; }
Random is often used in game development. Letβs play!
Thanks for your feedback!