codescracker


c++

C++ Program to Generate Random Numbers



« Previous Program Next Program »


Generate Random Numbers in C++

To generate random numbers in C++ programming, use the function rand() to generate and print random numbers. And if you want to generate different-different random numbers at each time when you compile and run the same program, then use the function srand() before generating the random numbers using the function rand() as shown here in the following program.

C++ Programming Code to Generate Random Numbers

Following C++ program generate 100 random numbers using rand() function of stdlib.h library:

/* C++ Program - Generate Random Numbers */
		
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
	clrscr();
	int i;
	for(i=0; i<100; i++)
	{
		cout<<rand()<<"\t";
	}
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program generate random numbers

C++ Programming Code to Generate Different Random Numbers

Following C++ program generates different-different random numbers each time when you run the program:

/* C++ Program - Generate Different Random Numbers */
		
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
	clrscr();
	srand();
	int i;
	for(i=0; i<20; i++)
	{
		cout<<rand()<<"\t";
	}
	getch();
}

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test