Printing 5 Non-Duplicate Random Numbers

Hello. I am currently studying out recursion for my Intro C++ class. However, I am struggling to understand how to print unique non-repeatable random numbers in an array. Any help would be greatly appreciated. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
	int arr[5];
	srand(time(NULL));
	for(int i = 0; i < 5; ++i) {
		arr[i] = rand() % 5;
		for(int j = 0; j < 5; ++j) {
			if(arr[j] == arr[i]) main();
		}
	}
	
	for(int k = 0; k < 5; ++k) {
		cout << arr[k] << " ";
	}
	
	return 0;
}
Last edited on
Don't call main(). It's a special function that is only to be used as the entry-point to the program.

If you want 5 unique random numbers from in range [0, 4] inclusive, the simplest thing to do would be to generate them in order, and then shuffle them.

e.g. something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    
    const int N = 5;
    
	int arr[N];
	srand(time(NULL));
	
	for (int i = 0; i < N; ++i) {
	    arr[i] = i;
	}
	
	for (int i = 0; i < N; i++)
	{
	    int index_A = rand() % N;
	    int index_B = rand() % N;
	    
	    // swap two random indices
	    // see also: std::shuffle which does a much better job than rolling your own.
	    int temp = arr[index_A];
	    arr[index_A] = arr[index_B];
	    arr[index_B] = temp;
	}
	
	for(int k = 0; k < 5; ++k) {
		cout << arr[k] << " ";
	}
	
	return 0;
}


If you are required to use some sort of recursion, then make another function and call that recursively, not main.

BTW, aside from the illegal recursion, the issue with your code is a logic one. Inside your "j" inner loop, you compare the values of arr[0..4]. But you only assigned arr[0]. arr[1..4] on the first loop don't have valid values.
Last edited on
Topic archived. No new replies allowed.