generate 20 distinguish random numbers

I want to generate random numbers from 1 to 20.
how can i do it?

I did something like this .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>
/* function main begins program execution */

int main(void) 
{
    int i, j ;                           /* counter */
	/* loop 20 times */
	for (i = 1; i <= 20; i++) 
    {
       /* pick random number from 1 to 6, but random numbesr 
       shoudl not be duplicte. and output it */
		printf("%d ", 1 + (rand() % 20));
            
    
	} /* end for */
	return 0; /* indicates successful termination */
} /* end main */


but i don't need duplicate random numbers.
how can i get it?
Pls help me. thanks
Insert the elements 1 to 20 in a list.
set initial i = 20.
generate random number between 1 and i.
output the ith list number and delete that number from the list.
decrement count and repeat till you have all the twenty numbers.
You could have a vector of numbers that have already been generated and check any newly generated numbers against that.

Or, since you seem to be using C, an array.
Create an array of 20 ints along with a count of how many random numbers are in the array.

When you generate a random number, check if it's already in the array. If it is, skip it and generate another random number.

You will need to change your for loop to a while loop since you won't know in advance how many times you will need to call rand() to get a unique random number.

Hye @abstractionAnon, Can u pls explain your answer with modification in my program. thanks
use can use shuffle algorithm to randomly rearrange the numbers 1 to 20 preinserted in an array.
Topic archived. No new replies allowed.