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.
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.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main() {
constint 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.