The below is a code to find number of words in a given sentence using recursion.
It seems that the two given "cout" statements result in different outputs and i cannot seem to understand the reason why?
#include <iostream>
using std::cin;
using std::cout;
int count_end(char *a, int start, int ctr) {
if (a[start] == '.') {
cout << ctr << "\n";
return ctr;
}
else if (a[start] == ' ' && a[start - 1] != ' ') {
ctr++;
}
start = count_end(a, start + 1, ctr);
return ctr;
}
int main() {
char sentence[1000];
cin.getline(sentence, 1000);
int x;
x = count_end(sentence, 1, 1);
cout << "is count" << x << "\n";
return 0;
}
I tried writing cout statements in later part of codes to judge the control flow. It seems the control flow is fine. I know of different ways to implement the same thing which give the correct output but I wonder why this particular method doesn't work.
The reason for your problem is the following: You never return the number of words to the initial function call. The initial function call returns the initial ctr value that was passed to it, because you never set it to a different value. Therefore you need to implement the function like this:
To sum it up:
You must return the value from the inner function to the function that called it before, instead of returning the initial ctr value.