random number

Apr 6, 2013 at 10:51pm
i want to make a program in which i have to display an array of random number from 1 to 10 .and the number should be shuffled but each number can occur only once ..
every time i run the program using random function it gives the same number again and again i have also used s rand but it is of no use
Apr 6, 2013 at 11:00pm
Did you seed using time?

srand (time(NULL));
Last edited on Apr 6, 2013 at 11:00pm
Apr 7, 2013 at 10:54am
yes
Apr 7, 2013 at 11:10am
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int r=0;
for(int i=1;i<=10;i++)
{
srand(time(NULL));
r=rand()%10+1;
cout<<r<<endl;
}
getch();
}

this is not exactly the program i want but this is an example of the problem im facing iam getting the output 10 times 5 .
Apr 7, 2013 at 11:47am
You are resetting the seed on every pass through the for loop. That will force it to generate the same random number each time (except on the rare occasion where the time changes to the next second during execution).

Place the srand call at the very start of main(), before any other processing. Don't put it inside a loop.

Apr 7, 2013 at 12:58pm
ohh thankkks i got it :)
Apr 7, 2013 at 3:51pm
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int r=0,b=0;
int a[10];
int j=0;
srand(time(NULL));
a: for(int i=0;i<=9;i++)
{
r=rand()%10+1;
a[i]=r;


if(r==a[i])
{
j++;

}
if(j>0)
{

b=rand()%10+1;
a[i]=b;
b=0;
r=0;
j=0;
}


else
{
goto a;
}
}
for(int j=0;j<=9;j++)
{
cout<<a[j];
cout<<endl;
}


getch();
}
what is wrong with it is not working ..iam not getting shuffled and unrepeated array
Apr 7, 2013 at 6:40pm
You made too complicated thing... @hamshid (9)
Apr 7, 2013 at 7:10pm
One approach is to fill the array with the sequence of numbers 1,2,3 ... 9, 10
After that, shuffle the array.
Topic archived. No new replies allowed.