Saturday, April 19, 2025

C++ Random Numbers

To generate random number, we will use rand() function. 

Please note, cstdlib must be imported for rand() function to work.

Inside main() section we will establish variable r that is result of rand() function.

To use for loop to generate a list of random numbers, there must be starting point established. In this case initial integer x will have value 0. That's our starting point while looping.

This code will work to some degree, but problem arises when we realize that every time when we run our program random numbers will be same. We will fix our code.

But first run this code multiple times to see what is happening:

#include <iostream>
#include <cstdlib>

using namespace std;

int main() {

    int r = rand();
    int x = 0;

    for (x; x <=20; x = x + 1) {
        cout << rand() << endl;
    }

    return 0;

}

Result:

18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
28145
23281
16827
9961
491
2995
11942
4827
5436
32391
14604

Process returned 0 (0x0)   execution time : 0.217 s
Press any key to continue.

Now we will fix things. First thing to do is import of ctime.

Then we will call srand() function and pass to it time() function with argument 0.

Rest of program is the same as in the first example:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {

    srand(time(0));
    int r = rand();
    int x = 0;

    for (x; x <=20; x = x + 1) {
        cout << rand() << endl;
    }

    return 0;

}

Result after first run: 

23852
19756
6004
7158
3533
32224
20942
19137
7716
21498
8810
10097
18113
8021
27907
19690
9425
32508
12488
26795
28319

Process returned 0 (0x0)   execution time : 0.163 s
Press any key to continue.

Result after second run:

15488
25268
14163
10738
28176
17782
11505
25261
7521
14398
10925
24188
25905
24669
8168
29001
9100
22079
27560
17683
17740

Process returned 0 (0x0)   execution time : 0.063 s
Press any key to continue.

Nice.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...