Help with counting array elements- C programming

Given

an int variable k,
an int array incompletes that has been declared and initialized ,
an int variable nIncompletes that contains the number of elements in the array ,
an int variable studentID that has been initialized , and
an int variable numberOfIncompletes,

write code that counts the number of times the value of studentID appears in incompletes and assigns this value to numberOfIncompletes.

You may use only k, incompletes, nIncompletes, studentID, and numberOfIncompletes.


First attempt:

1
2
3
4
5
6
7
while (k < nIncompletes && !numberOfIncompletes)
{
if(incompletes[k] == studentID)
numberOfIncompletes = true;
k++;

}



Second attempt:

1
2
3
4
for(k=0; k < nIncompletes;k++) {
if(incompletes[k] == studentID)
numberOfIncompletes++ ;
}
Last edited on
Correct code :

1
2
3
4
5
6
 numberOfIncompletes=0;
for (k=0; k<nIncompletes; k++){
    if (incompletes[k] == studentID){
        numberOfIncompletes++;
    }
}
Topic archived. No new replies allowed.