T
Tadpole
Hi,
I am trying to print 5 unique random numbers 0 to 4. But each time I
print, I get funny result. What is wrong with my program? Please see
below.
Rgds
Khoon
//Result
X[0]= 0
X[1]= 3
X[2]= 4208527
X[3]= 4
X[4]= 4208527
Press any key to continue . . .
//Program
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{ int x=0;
int X[5];
srand (time(NULL));
X[0] =rand()%5;
x=rand()%5;
if (x!=X[0])
X[1]=x;
x=rand()%5;
if ((x!= X[0])&& ( x!=X[1]))
X[2]=x;
x=rand()%5;
if ((x!= X[0]) && (x!=X[1])&& (x!= X[2]))
X[3]=x;
x=rand()%5;
if ((x!= X[0]) && ( x!= X[1]) && ( x!=X[2]&& x!=X[3]))
X[4]=x;
for (int i=0; i<5 ; i++)
printf ("X[%d]= %d \n",i, X);
printf ("\n");
return 0;
}
I am trying to print 5 unique random numbers 0 to 4. But each time I
print, I get funny result. What is wrong with my program? Please see
below.
Rgds
Khoon
//Result
X[0]= 0
X[1]= 3
X[2]= 4208527
X[3]= 4
X[4]= 4208527
Press any key to continue . . .
//Program
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{ int x=0;
int X[5];
srand (time(NULL));
X[0] =rand()%5;
x=rand()%5;
if (x!=X[0])
X[1]=x;
x=rand()%5;
if ((x!= X[0])&& ( x!=X[1]))
X[2]=x;
x=rand()%5;
if ((x!= X[0]) && (x!=X[1])&& (x!= X[2]))
X[3]=x;
x=rand()%5;
if ((x!= X[0]) && ( x!= X[1]) && ( x!=X[2]&& x!=X[3]))
X[4]=x;
for (int i=0; i<5 ; i++)
printf ("X[%d]= %d \n",i, X);
printf ("\n");
return 0;
}