Hey guys , as from what i read up , the function srand() and rand() are able to give u random numbers if they are being run one time only. What i am trying to do is to produce a set of random and unique numbers from 1 - 10.

int main ()
{

    int num[10];
    

srand((unsigned)time(0));

int random_integer;

for(int index=0; index<10; index++){

random_integer = rand()%10;
num[index] = random_integer;
for(int i = 0;i< 10 ; i++)
{
    if(num[i] == random_integer){
        random_integer = rand()%10;
        num[i] = random_integer ;
    }
    
}
        cout << random_integer << endl;

}

What i try to do is to generate the random number, store it inside a array. Then within that for loop , i would do a check to see if the number already exist . if it does, another random number will be generated.

The problem i am facing is that, the number does not seem to replace itself. I tried various ways of playing around with the loop but to no avail. Hope for some help. Ty.

Your if statement is always going to be true no matter what starting off from the very first iteration.

Oh yeah , i deleted that line off already, but same mistakes are coming up

using namespace std;
int main ()
{

    int num[10];
    

srand((unsigned)time(0));

int random_integer;

for(int index=0; index<10; index++){

random_integer = rand()%10;
for(int i = 0;i< index ; i++)
{
    if(num[i] == random_integer){
        random_integer = rand()%10;
        num[i] = random_integer ;
    }
    
}
        cout << random_integer << endl;

}
   
    

}
random_integer = rand()%10;
for(int i = 0;i< index ; i++)
{
    if(num[i] == random_integer){    // Why are replacing a good number with a new number?
        random_integer = rand()%10;  // How do you know the new number isn't the same as the old number?
        num[i] = random_integer ;    // and what are the initial values of num when you start? (don't assume, check it out)
    }
    
}

i think something like this would work:

int nIndex = 0;
int nSize = sizeof(num)/sizeof(int);

while(nIndex < nSize) 
{
	int rndNumber = rand()%10;

	for(int i = 0; i < nSize; i++)
	{
		if(num[i] == rndNumber)
			break;

		if(i == nSize-1)
			num[nIndex++] = rndNumber;
	}
}
This article has been dead for over six months. Start a new discussion instead.