Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Random Number Generation in C programming

August 25, 2013 Posted by: GPA Views: 526 0 comments

Sometimes you need random numbers to solve your problems. C provides function rand() that helps you in generation random numbers for your application. The rand function generates an integer between 0 to some random max value. Standard C that the value of random max value is least 32767, which is the maximum value for a two-byte (i.e., 16-bit) integer. For using this function we must include <stdlib.h> header. Function rand() produces integers in the range 0 to max. That's why in our example we add 1 to the result. 

In this lesson you will know how to create a random number and example will help you easily understand and use the code to generate random numbers in your C application. Let's develop a program to simulate 10 rolls of a six-sided die and print the value of each roll.

 

Example:

   

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
   int i=0;
   int randnumber;
   for(i=0;i<10;i++){
       //select random number from 1 to 6 and show result
        randnumber=1 + ( rand() % 6 );
       printf("%d ",randnumber);
   }
   printf("\n");
   system("PAUSE");
  return 0;
}

Output

Random Number Generation in C

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe