A very simple C program on how to generate random number using rand() built-in function

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: A very simple C program on how to generate random number using rand() built-in function

To show: How to use the rand() C function from standard library to generate random numbers

 

 

// A simple random number function generator, rand()

#include <stdlib.h>

#include <stdio.h>

 

int main(void)

{

int i;

 

printf("Ten random numbers from 0 to 99\n\n");

 

// the for loop, iterating 10 times

for(i=0; i<10; i++)

{

// random number function generator

printf("Generated random number %d = %d\n", i, rand()%100);

}

printf("\n");

return 0;

}

 

Output example:

 

Ten random numbers from 0 to 99

 

Generated random number 0 = 41

Generated random number 1 = 67

Generated random number 2 = 34

Generated random number 3 = 0

Generated random number 4 = 69

Generated random number 5 = 24

Generated random number 6 = 78

Generated random number 7 = 58

Generated random number 8 = 62

Generated random number 9 = 64

 

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index