-
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 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:
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.
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
|