C/C++ - Generate a random number

19. April 2012 21:57

 

This is a short example for generating a random number in C/C++. It is actually easy to do. In this case we can produce a random number between 0 and 10 and print it out.

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


int main(int argc, char **argv) {

	srand(time(NULL));

	for(int i =0;i<10;i++) {
		int r = rand() % 10;
		printf("%d\n", r);
	}

	return 0;
}

 

The solution above will only work for generating a number from 0 to RAND_MAX which is typically 32768.

E-mail Kick it! DZone it! del.icio.us Permalink