Random array without duplicates

I want a random numbered array, I thought this should work But the array still displays duplicates. However if I put cout something instead of continue it prints it.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int func (int);
int main() {
	int arr[20], temp, num;
	srand (time(0)*time(0) - time(0)*4 );
	for (int i = 0; i < 20; i++){
	num = 10 + rand () % 90;
	if (num < 10 || num > 100){
		cout << num;
		cout << "error";
		return 0;
	}
	else{
		
	for (int x = 0; x < i; x++){
   if (arr[x] == num)
   continue;
   
   else 
   arr[i] = num;
	}
	}
	}
		cout << "Array is: " << endl;
	for (int j = 0; j < 20; j++)
	cout << arr[j] << "  ";
	cout << endl;
	
	for (int pass = 1; pass < 20; pass++){
		for (int z = 0; z < 19; z++){
		if ( arr[z] > arr[z + 1] ) {                     
                   temp = arr[z];                                
                   arr[z] = arr[z + 1];                          
                   arr[z + 1] = temp;                            
}
	}
	}
	cout << "Sorted array is: "<< endl;
	for (int j = 0; j < 20; j++)
	cout << arr[j] << "  ";
	cout << endl;
	
	return 0;
}
This is the loop you seems to have problem with.
1
2
3
4
5
6
for (int x = 0; x < i; x++) {
	if (arr[x] == num)
		continue;
	else 
		arr[i] = num;
}

Note that continue simply jumps to the next iteration of the loop so the loop could be written like this:
1
2
3
4
for (int x = 0; x < i; x++) {
	if (arr[x] != num)
		arr[i] = num;
}

The loop writes the number to the array if it's equal to any of the previous numbers in the array. It also prevents the first number to be written to the array because when i == 0 it never even enters the loop.

What you could do instead is to check if the value exists in the array by using a loop, and then after the loop you write the number to the array if it didn't already exist. You also need to think about what you should do if the number already exists in the array.
Last edited on
Thanks for the point, problem solved.
Topic archived. No new replies allowed.