C++ | Generating Random Number between 2 Numbers

Introduction

This is a program for generating random number between two numbers. The program takes higher limit and lower limit from user and gives a random number between the limit. The program is extendable. Go enjoy the program. Lets begin……

Program for generating random number between two numbers.

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
//clear the screen.
clrscr();
//declare variables as int.
int high,low,random;
//get the data.
cout<<"Enter higher limit:";
cin>>high;
cout<<"Enter lower limit:";
cin>>low;
//generate random number
random = (rand() % (high-low+1) + low);
//print the numbers
cout<<random<<endl;
//get character
getch();
}

Output

Enter higher limit:100
Enter lower limit:15
66

How does it work.

  1. You enter the limits.
  2. The number is generated and printed.

Extending it.

The program is extendable. This is a basic concept of c++ and can be used in any program. Go extend it.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ and ‘stdlib.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare variables.
  5. Add cout and cin to get limits.
  6. Generate a number and save it in a variable.
  7. Add cout to print the number.
  8. Get character.

At the end

You learnt creating the C++ program for generating random number between given limit. So now enjoy the program.

Please  share it.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: