Reputation: 7
here is the instructions for code I am trying to write:
Consider the testPIN function used in Program 7-21. For convenience, we have reproduced the code for you below. Modify this function as follows: change its type to int change its name to countMATCHES make it return the number of corresponding parallel elements that are equal
I have this code here:
int countMatches(int custPIN[], int databasePIN[], int size) {
for (int index = 0; index < size; index++) {
if (custPIN[index] == databasePIN[index])
return index;
}
return size;
}
Where exactly am I failing to do? Is it that I am infinitely stuck in this loop or is it something else?
Upvotes: 0
Views: 269
Reputation: 166
The problem is that your function trying return more than once. If condition is true then you will return index but also will trying to return the size (which is not possible) where if its false then it will only return size Change the code as follows :
int countMatches(int custPIN[], int databasePIN[], int size) {
int e;
for (int index = 0; index < size; index++){
if (custPIN[index] == databasePIN[index]) {
e++;
}
}
if(e!=0)
return e;
}
Hope this will help you.
Upvotes: 0
Reputation: 1921
As per description your code should be like below :
int countMatches(int custPIN[], int databasePIN[], int size)
{
int counter =0;
for (int index = 0; index < size; index++) {
if (custPIN[index] == databasePIN[index])
counter++;
}
return counter;
}
Upvotes: 1
Reputation: 654
Perhaps in the first line of the function you want to initialise a new counter variable to 0, and then, if the customer and database pins match, you increment it. In the end, instead of returning the size, perhaps you want to return the counter, which now has been incremented for each matching character.
Upvotes: 0