I am writing a function for a program that asks the user to input a “student id number” and stores it in the array. Before storing the function has to check if we don’t already have that number in the array because the student numbers must be unique. It also includes a pointer to an int that represents how many student numbers have been stored so far.
I have written some code but it is not working 🙁 would anyone please shed some light?
This is my code:
void update_student_id(int a[], int*pnum)
{
int temp,h;
for (h=0;h<=*pnum;h++){
printf(">>>Student ID:");
scanf("%d",&temp);
if (temp==a[h]){
printf("ERROR:%d has already been used!\n",temp);
h=*pnum+1;
}
else
h=*pnum+1;
}
a[*pnum]=temp;
*pnum++;
Ok, new version with 2 for loops, improving but not working yet 🙁
void update_student_id(int a[], int*pnum)
{
int temp,h,i;
for (h=0;h<=*pnum;h++){
printf(">>>Student ID:");
scanf("%d",&temp);
for(i=0;i<=*pnum;i++)
if (temp==a[i]){
printf("ERROR:%d has already been used!\n",temp);
i=*pnum+1;
}
else i++;
}
a[*pnum]=temp;
(*pnum)++;
}
Problem solved with Dennis’ help, final code:
void update_student_id(int a[], int*pnum)
{
int temp,h,i,canary;
for (h = 0; h <= *pnum; h++) {
printf(">>>Student ID:");
scanf("%d", &temp);
canary = 0;
for (i = 0; i < *pnum; i++) {
if (temp == a[i]) {
printf("ERROR:%d has already been used!\n",temp);
canary = 1;
break;
}
}
if (canary == 0) {
a[*pnum] = temp;
(*pnum)++;
break;
}
}
return;}
So, the main thing I see is that after you scan the number, you’re not actually checking to see if the number is already in the array; you’re only checking to see if it’s at a particular index.Being more specific, you need more than that if statement inside your for loop; perhaps another loop that looks through the indices used up so far.EDIT: The biggest problem is that in the else clause, don’t increment
i. Second, you need some canary variable to let you know if you’ve made that call to printf.For example, here’s my idea for those loops: