Blog Archive

RPGLE Generate Random Number using rand(), srand() and clock() C funcions

Each time you call rand(), it will give you a number. They'll look like random numbers, but really it's just the result of a complicated mathematical formula. The problem with this is if you run your program and it gives you 53, 1143, 543, 9853 then the next time you run your program, it will give you the exact same sequence of numbers. That's annoying.

So what you do is called "seeding the random number generator". That's basically just telling it "okay, start from here". If each time you tell it to start from a different number, then the sequence will be different each time you run your program.

So how do you get a number that's going to be unique each time you run your program? There are various possibilities, but the most obvious is the date and time. Obviously, next time you run your program, it will be a different time of day, or a different day, or both.

So if you use srand(time()) to seed the random number generator with the current time, you'll get a different sequence of "random" numbers each time you run your program.

RPGLE Sample Code to Generate Random Number

h option(*nodebugio) dftactgrp(*no) bnddir('QC2LE')                    
 * Prototype to C "rand" function                                      
d Rand            PR            10I 0 ExtProc('rand')                  
 * Prototype to C "srand" function                                     
d SRand           PR                  ExtProc('srand')                 
d   iSeed                       10U 0 VALUE                            
 * Prototype to C "clock" function                                     
d GetTime         PR            10I 0 ExtProc('clock')                 
 * Global variables                                                    
d RandomNumber    S             10I 0                                  
d ClockTicks      S             10I 0                                  
d SeedValue       S             10U 0                                  
     ClockTicks = GetTime;                                             
     SeedValue = ClockTicks;                                           
     RandomNumber = Rand();                                            
     dsply RandomNumber;                                               
     *inlr = *on;              

Recommended Reading