Hi I\'m having trouble understanding something... So I was working on a program
ID: 3907317 • Letter: H
Question
Hi I'm having trouble understanding something... So I was working on a program that counts the number of times a certain value occurs in an array. This is what I came up with first:
int numberOfTimes(int array[], int position, const int SIZE, int value)
{
while(position<SIZE)
{
if(array[position]==value)
return 1+numberOfTimes(array,position+1,SIZE,value);
else
return numberOfTimes(array,position+1,SIZE,value);
}
}
int main()
{
const int SIZE=9;
int array[SIZE]={1,2,3,3,4,5,6,7,8};
int value=3;
cout<<numberOfTimes(array,0,SIZE,value);
}
However, by doing this I got a warning saying: Control reaches end of non-void function. So I looked at the answer and this is it:
int numberOfTimes(int array[], int position, const int SIZE, int value)
{
if(position>=SIZE)
return 0;
else if(array[position]==value)
return 1+numberOfTimes(array,position+1,SIZE,value);
else
return numberOfTimes(array,position+1,SIZE,value);
}
int main()
{
const int SIZE=9;
int array[SIZE]={1,2,3,3,4,5,6,7,8};
int value=3;
cout<<numberOfTimes(array,0,SIZE,value);
}
Can someone explain why you cant do a while loop like I did at first for this problem? Thanks.
Explanation / Answer
(*) Please feel free to ask anything regarding the answer through comments.
After analyzing your code, the compiler sees that a return statement will be executed for all values of positon less than SIZE. However, if the value of position is greater then or equal to SIZE, the code would reach the end of the function numberOfTimes without a return statement; that is why the compiler issues a warning.
Note that it may not be possible for position to be set greater then SIZE because of the while statement. However, the compiler does not know any of that, so it thinks that position could have any value.
In case of the second code you added an if statement that covers the possibility for value of position being greater than or equal to SIZE with a return statement; thats why the compiler does not show any warning that time.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.