0

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?

6
  • 9
    You must return something from a function if it's return type isn't void (except for main).You don't return when i<26. Commented Oct 29, 2018 at 14:29
  • 2
    Learn to love compiler warnings and NEVER ignore them! This code has undefined behavior, and compiler will warn you about it. Commented Oct 29, 2018 at 14:32
  • 2
    I have always thought c++ warnings/errors were badly named, I personally read "warning" as "error" and "error" as "fatal error" Commented Oct 29, 2018 at 14:33
  • Hi there @SergeyA , thanks for your reply.I didn't get any warnings. Commented Oct 29, 2018 at 14:37
  • @mujtaba1747 "I didn't get any warnings." Did you enable them? Commented Oct 29, 2018 at 14:39

2 Answers 2

4

Your non-void function does not return anything when i is less than 26 and this is undefined behavior. If you checked/turned on the compiler warnings you would see the warning:

warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

Removing the already pointless else fixes that issue:

#include <iostream>
using namespace std;

int su(int sum,int i)
{
    if(i<26)
    {
        sum=sum+i+su(sum,i+1);
        cout<<sum<<endl;
    }
    // Removed the else. Always returns something
    return sum;
}

int main() {
  std::cout << su(0, 0) <<std::endl;
}

Output:

25
49
72
94
115
135
154
172
189
205
220
234
247
259
270
280
289
297
304
310
315
319
322
324
325
325
325

Always firstly make sure your recursive function eventually gets out of the loop and returns a value in case it's not void. A much simpler and cleaner way would be like this (a bit like the classic factorial function):

#include <iostream>

int sum (int i) {
  if(i == 1) {
    return 1;
  }
  return i + sum(i-1);
}

int main() {
  std::cout << sum(25) <<std::endl;
}

Output:

325

If you add std::cout to see what's going on under the hood:

#include <iostream>

int sum (int i) {
  std::cout << i << std::endl; // current integer
  if(i == 1) {
    return 1;
  }
  return i + sum(i-1);
}

int main() {
  std::cout << sum(25) <<std::endl;
}

The output is as expected:

25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
325
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot for answering.However I am not able to understand the pattern followed by the variable 'sum' which is : 25 49 72 94 115 135 154 172 189 205 220 234 247 259 270 280 289 297 304 310 315 319 322 324 325 325 325 Now its more of a mathematical doubt but still it would be nice if you could help me with this too !!
0 + 25 = 25; 0 + 25 + 24 = 49; 0 + 25 + 24 +23 = 72; 0 + 25 + 24 +23 + 22 = 94 and so on. This mere recursion, nothing else. Just do more exercises on recursion to get the hang of it.
Thanks,are there any suggestions from your side as to from where can I practice problems on recursion and learn more about the concept?
0

Your function doesn't return anything if not at the end of the recursion. Remove the else keyword it should work.

4 Comments

Sadly, it will return something - because it has to. The problem is the compiler hasn't been told what to return, so it just returns what you hope to be junk.
I know, by "doesn't return anything" I meant "unusable stuff". (How many times did I forget a return in recursive functions ?? Too many, obviously)
@UKMonkey It's UB, so it doesn't have to return anything. For example the function call might be omitted by the compiler if it can prove it's always UB. Or it might just crash at the end of the function. Though in this case it certainly appears that the function returns something.
Most likely, the user will end up with whatever was in the accumulator when the function returns, so "it will return something" is a fair statement. The program may appear to function. But it's also true that the code could theoretically do anything, or nothing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.