Click here to Skip to main content
15,921,113 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
class program5 //----STACK OVERFLOW EXCEPTION
   {
           public int sum(int n)
           {
            int s;
            s = n + sum(n-1);
            return s ;
           }
       static void Main(string[] args)
       {
           program5 p = new program5();
           p.sum(5);
       }

   }
Posted

Surely a homework!

It's a recursive method that probably is doing sum of natural numbers. Following should be ok:
C#
public int sum(int n)
{
     if(n==1)
        return 1;

     int s;
     s = n + sum(n-1);
     return s ;
}
 
Share this answer
 
The most common cause of stack overflow is excessively deep or infinite recursion.So you need to terminate with some condition.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900