Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have written a recursive code to calculate sum of first n numbers, as I am not returning s, but code is working. Why?

I have written a recursive code in CPP to calculate sum of first n numbers, as I am not returning s, but code is working fine. Is ‘s’ variable is shared with all functions.

#include<iostream>
using namespace std;

int sum(int n){
    int s = 0;
    if(n == 0)  return 0;
    s = n + sum(n - 1);
}

int main(){
    int n; 
    cin >> n;
    int s = sum(n);
    cout << s;
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should return an integer from sum if n is not equal to 0.

#include<iostream>
using namespace std;

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

int main(){
    int n; 
    cin >> n;
    int s = sum(n);
    cout << s;
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading