I wrote a program to print the sum of first 25 natural numbers using a recursive function. It went fine and I also got the correct output(ie 325). After that I played a little with my code just to see what happens.
Here is the code :
int su(int sum,int i)
{
if(i<26)
{
sum=sum+i+su(sum,i+1);
cout << sum << endl; // I added this line to see what happens.
// This line wasn't needed but I still
// added it.
}
else
return sum;
}
When I ran this code, it printed weird values of the variable sum.
Here is a screenshot the output : output
The sum of first 25 natural numbers is 325 but that doesn't even show up anywhere in the output. Instead, I got different numbers as in my output.
However when I remove the line cout << sum << endl; from the if statement, I get the expected sum (ie 325).
What is the cause of that?
void(except formain).You don't return wheni<26.