Fill an array with nonrepeating numbers, randomly generated

I'm trying figure out how to use a random number generator to fill an array with numbers none of which is repeated. For this, I've been doing small-scale test-tries with an array that will hold 5 numbers.

I'm using an if else statement to reject numbers that are already present in the array. I haven't figured out how to generate new numbers (that haven't already been used).

But my real concern at this point is that the if else statement doesn't seem to do anything at all.

Here is my code:

#include "stdafx.h"
#include <iostream>
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <cstdlib>
using namespace std;
using std::rand;
using std::srand;



int main()
{

srand(time(0));
int c[5] = { 0,0,0,0,0 };
for (int i = 0; i < 5; i++) {
int x = rand() % 5 + 11; //This is a test, so I'm going for
//5 consecutive integers
if (c[0] != x && c[1] != x && c[2] != x && c[3] != x && c[4] != x)
{
c[i] = x;
}
else {
c[i] = 0; // This is to see if anything worked at all.
//int y = rand() % 5 + 21; [This and the following line attempt to
//c[i] = y; [generate new numbers that would be different.]
}
int j = i + 1;
cout << "Number " << j << " is " << c[i] << ".\n";
}
return 0;
}

Basically, the output is sequences such as 14, 11, 13, 11, 15 or 11, 11, 13, 15, 12.

So I imagine there is some much better way to do this, but I don't know what it is. Thanks in advance for any help you can offer.

Archie

Last edited on
Topic archived. No new replies allowed.