C Program to Generate Random numbers within a Range2 min read

In this tutorial, you will learn to generate random numbers within a range in C programming. But before that, you may go through the topic below if you do not know about the rand() and srand() function used in random numbers generation.

Here we will use srand() function provided in C to generate random numbers. The current time will be used to seed the srand() function.

C Program to generate random numbers within the range

Since the rand() will generate random numbers between 0 to max value, but instead of 0 we want to enter the lower range as well as the upper range so here is the trick we need to implement.

(upRange - lrRange + 1)) then add the lower range at the end.

Output:

Enter how many random numbers you want: 7
Enter the lower range: 10
Enter the upper range: 50

7 random numbers are:
22 29 24 33 18 41 11

Again execute the program but this time entered for 10 random numbers, start from 1 and give upper range 7.

Enter how many random numbers you want: 10
Enter the lower range: 1
Enter the upper range: 7

7 random numbers are:
1 3 7 7 5 2 1 5 1 2

Notice that the program is repeating the number as you requested for 10 random numbers but the range is limited to 7 numbers. Hence the program repeats the number.


MORE

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …
Read More

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …
Read More

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …
Read More

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More

Inverted Half Pyramid Pattern of Alphabets in C

In this tutorial, we will write a C program to print half Pyramid using alphabets/characters. Before that, you may go through the following topic in …
Read More