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

Can anyone explain why does this recursive function crash?

Why does this recursive (i’m not sure about it, the site i found this code said it was "recursive") code crash (i found this weird approach on Internet, but i’m honestly not understanding how it works) entering values >4000 (sometimes >4023, sometimes >4015, i really don’t understand…)…

#include <iostream>
unsigned long long int sum(unsigned long long int k)
{
    if (k > 0) {
        return k + sum(k - 1);
    }
    else {
        return 0;
    }
}
int main()
{
    unsigned long long int n;
    std::cout << "This program prints the sum of the first N natural numbers.\n\
Enter N: _";
    std::cin >> n;
    std::cout << "The sum is: " << sum(n) << ".\n\
Press any key to exit...";
    system("pause>nul");
    return 0;
}

while this, instead, does not?

#include <iostream>
int main()
{
    unsigned int n;
    std::cout << "Questo programma stampa la somma dei primi N numeri naturali.\n\
Prego inserire N: _";
    std::cin >> n;
    unsigned long long int tmp = 0;
    for (n; n != 0; --n) {
        tmp += n;
        //std::cout << tmp << ' ';
    }
    std::cout << "La somma \212: " << tmp << ".\n\
Premere un tasto per uscire...";
    system("pause>nul");
    return 0;
}

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

>Solution :

The recursive version uses a little bit of stack space every time it calls itself, so it is limited by the size of the stack and will crash if it calls itself too many times. It’s a classic stack overflow error.

The iterative second version doesn’t have that problem.

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