In: Computer Science
This is C++ programming
Given
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.
I tried this code down below but it's giving me a logical error:
numberOfIncompletes=0;
for (k = 0; k < nIncompletes; k++)
numberOfIncompletes=0;
for (k = 0; k < nIncompletes; k++)
{
if (incompletes[k] == studentID)
numberOfIncompletes ++;
numberOfIncompletes=studentID;
}
In above code, your mistake is you are incrementing numberOfIncompletes while found studentID in incompletes and you are also assigning studentID to numberOfIncompletes. That's wrong. You only need to increment count.
when you are performing numberOfIncompletes++, it will perform numberOfIncompletes = numberOfIncompletes + 1. Means it directly assigns to numberOfIncompletes. So here your problem is solved.
When you are writing numberOfIncompletes=studentID means every time it will give you studentID in numberOfIncompletes. That is wrong.
You can refer below code for your reference,
Here student ID is 2 and in incompletes it repeats 3 times. Thus, count of numberOfIncompletes becomes 3.
#include <iostream>
using namespace std;
int main()
{
int k;
int incompletes[10] = {1, 2, 4, 2, 3, 15, 8, 7, 1, 2};
int nIncompletes = 10;
int studentID = 2;
int numberOfIncompletes = 0;
for (k = 0; k < nIncompletes; k++)
{
//when studentID matches,increment numberOfIncompletes by 1
if (incompletes[k] == studentID)
numberOfIncompletes++;
}
cout<<numberOfIncompletes;
return 0;
}
Please refer below screenshot of code and output.
In your problem statement it is said that Write code that counts the number of times the value of studentID appears in incompletes and assigns this value to numberOfIncompletes. Here assigns the value means whatever count we are getting that assign to numberOfIncompletes. So, that's your mistake.