I want to generate numbers 1 to 4 in a random fashion using C programming.
I have made provision to print a[0]
directly in a while
loop and for any further element the program checks whether the new number from a[1]
to a[3]
is same as any of the previous elements. A function has been created for the same. int checkarray(int *x, int y)
.
The function checks current element with previous elements one by one by reducing the passed address. If it matches the value it exits the loop by assigning value zero to the condition variable (int apply
).
return apply;
In the main
program it matches with the int check
if check==1
, the number is printed or else the loop is repeated.
Problem faced: The number of random numbers generated is varying between 2 and 4. e.g
2 4 2 4 3 1 3 3 4
etc
Also repetition is there sometimes.
#include <stdio.h>
#include <conio.h>
int checkarray(int *x, int y);
void main() {
int a[4], i = 0, check;
srand(time(0));
while (i < 4) {
a[i] = rand() % 4 + 1;
if (i == 0) {
printf("%d ", a[i]);
i++;
continue;
} else {
check = checkarray(&a[i], i);
}
if (check == 1) {
printf("\n%d ", a[i]);
} else {
continue;
}
i++;
}
getch();
}
int checkarray(int *x, int y) {
int arrcnt = y, apply = 1, r = 1;
while (arrcnt > 0) {
if (*x == *(x - 2 * r)) {
apply = 0;
exit(0);
} else {
arrcnt--;
r++;
continue;
}
}
return apply;
}