
September 29th, 2011, 08:16 PM
#1
[RESOLVED] Recursive Function to form the sum of two positive integers a and b?
Hi all,
I'm new to csharp, 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:
Please enter first number: 4
Please enter second number: 9
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;
int addition;
Console.Write("Please Enter First Number: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Please Enter Second Number: ");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
addition = recSum(a, b);
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.
Please guide me.
Thanks a lot for your time.

September 29th, 2011, 08:51 PM
#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.

September 29th, 2011, 09:15 PM
#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, y1)
Code:
static int recSum(int x, int y)
{
return (y == 0) ? x : recSum(x + 1, y  1);
}
Rob

Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......
Tags for this Thread
Posting Permissions
 You may not post new threads
 You may not post replies
 You may not post attachments
 You may not edit your posts

Forum Rules

Click Here to Expand Forum to Full Width
This a Codeguru.com survey!
