C Reference function rand() generate a random number

This function of stdlib will generate a random number.

Usage of rand():

int rand (void);

Parameters:

The function rand() returns a pseudo-random integral number.
This number will be in the range 0 to RAND_MAX. The algorithm of rand() uses a seed to generate the series of numbers, this is why srand must be used to initialize the seed to some distinctive value.

The constant RAND_MAX is defined in standard library (stdlib).

The random numbers are delivered from a predetermined range.

Return value:

Will return an integer value between 0 and RAND_MAX.

Source code example of rand():



	#include<stdio.h>
	#include<stdlib.h>
	#include<time.h>

	int main ()
	{
		int number, input;
		/* initialize random seed: */
		srand ( time(NULL) );
		/* Generate a random number: */
		number = rand() % 10 + 1;
		do {
				printf ("Guess the number (1 to 10): ");
				scanf ("%d",&input);
				if (number > input)
					printf ("The number is higher\n");
			} while (number!=input);
		printf ("That is correct!\n");
		return 0;
	}

This entry was posted in C Reference stdlib.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 4 responses to “C Reference function rand() generate a random number”

Why not let us know what you think by adding your own comment!

  1. Tzrinz on October 28th, 2013:

    thanx:)

  2. Aki on November 1st, 2013:

    Had the idea for 1-10 and thankfully yours is the only one i found that helped me

  3. nisha on December 11th, 2013:

    a C program to find the total number of
    students with Pass and Fail grades in a class
    of 35

    please can reply

  4. asdf on April 16th, 2014:

    nisha, if pass is 50marks and below that is fail then,this is the solution to count the passes and fails.

    int students,pass=0,fail=0;
    for(students=35;students=50)
    {
    pass=pass+1;
    }
    if(marks<50)
    {
    fail=fail+1;
    }
    }
    printf("Fail %d\n",fail);
    printf("Pass %d\n",pass);