Home > Mobile >  Can anyone explain why does this recursive function crash?
Can anyone explain why does this recursive function crash?

Time:04-02

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;
}

CodePudding user response:

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.

  • Related