You set the flag to 0
if the number already was chosen, so you should test while(flag == 0)
, and re-set the flag to 1
at the start of the loop:
do {
flag = 1;
randNum = (rand()%10 + 1); //generate random ID for each student
for (j = 0; j < i && flag == 1; j++) { //search array for matching numbers
if (students[j].id == randNum) {
flag = 0;
}
}
}
while (flag == 0); //set condition
Now, flag == 0
means "already seen, try again" and flag == 1
means "it's a new number, go ahead and write it to the array".
Also, you only have the array slots for indices < i
filled, so the comparison loop should not go to 9
, but only to i-1
.