CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

Thread: [RESOLVED] Recursive Function to form the sum of two positive integers a and b?

1. Junior Member Join Date
Sep 2011
Posts
2

[RESOLVED] Recursive Function to form the sum of two positive integers a and b?

Hi all,

I'm new to c-sharp, so I will appreciate if you guys go easy on me.

I have to write a recursive function to form the sum of two positive integers a and b. I have to test the program by calling it from a main program that read two integers from the keyboard and uses your function to complete and print the sum, along with two numbers. I have to call my function recSum.

INPUT:

OUTPUT:

From start of body: 4 9
From start of body: 3 9
From start of body: 2 9
From start of body: 1 9
From start of body: 0 9
From end of body: 1 9
From end of body: 2 9
From end of body: 3 9
From end of body: 4 9

The sum of 4 and 9 is 13.

<---------THIS IS WHAT I HAVE SO FAR-------->

Code:
static void Main(string[] args)
{
int a, b;

Console.WriteLine();

Console.WriteLine("\nThe sum of {0} and {1} is {2}\n",a,b,addition);

}

static int recSum(int x, int y)
{
int result = 0;

if (y >= 0)
{

for (int i = x; i >= 0 ; i--)
{
Console.WriteLine("From start of body: {0} {1}", i, y);

if (i == 0)
{
for (int j = i+1; j <= x; j++)
{
Console.WriteLine("From end of body:   {0} {1}", j, y);
}
}

}
result = x + y; //should be a recursive function

}return result;
}
The program is working fine but if you notice, it does not have a recursive function.
So how do I create a recursive function for this calculation.

Thanks a lot for your time.  Reply With Quote

2. Junior Member Join Date
Sep 2011
Posts
2

Re: Recursive Function to form the sum of two positive integers a and b?

I figured it out by myself.

Code:
static int recSum(int x, int y)
{
int result = 0;
if (y == 0)
{
return (x);
}
else
{
result = recSum(x + 1, y - 1);
}
return result;
}
Okay so what it basically does is that it will increase x by one until y is equal to 0.  Reply With Quote

3. Re: [RESOLVED] Recursive Function to form the sum of two positive integers a and b?

Nice. Sometimes (but only if it is clear and obvious) you can use an 'inline if'.

The following code says:

If y is 0 then return x else return the result of recSum(x+1, y-1)

Code:
static int recSum(int x, int y)
{
return (y == 0) ? x : recSum(x + 1, y - 1);
}  Reply With Quote

add, csharp, function, recursive  Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•