473,779 Members | 2,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Don't understand output from this recursion code

14 New Member
class Program
{
public void test(int i) {
if (i > 0)
{
test(--i);
}
Console.WriteLi ne(i);
}

static void Main(string[] args)
{
Program p = new Program();
p.test(5);
Console.ReadKey ();
}
}

The output is 0 0 1 2 3 4

I dont quite understand.
I thought that the Console.WriteLi ne(i); wont execute until i <= 0

and why is that the 0 comes first?

Correct me if im wrong im just new to programming.
Is it because that when a function is called is uses the stack?
so the while the condition is true it keeps calling its self and the first output was actually 4 (because of the pre --yy) but the instruction was on the lowest part of the stack thats why it came out last.

4 3 2 1 0 0 then pops out like 0 0 1 2 3 4

Is that how stack work?

is there a threading happening here?
Jul 29 '08 #1
7 1266
IanWright
179 New Member
class Program
{
public void test(int i) {
if (i > 0)
{
test(--i);
}
Console.WriteLi ne(i);
}

static void Main(string[] args)
{
Program p = new Program();
p.test(5);
Console.ReadKey ();
}
}

The output is 0 0 1 2 3 4

I dont quite understand.
I thought that the Console.WriteLi ne(i); wont execute until i <= 0

and why is that the 0 comes first?

Correct me if im wrong im just new to programming.
Is it because that when a function is called is uses the stack?
so the while the condition is true it keeps calling its self and the first output was actually 4 (because of the pre --yy) but the instruction was on the lowest part of the stack thats why it came out last.

4 3 2 1 0 0 then pops out like 0 0 1 2 3 4

Is that how stack work?

is there a threading happening here?
No, it isn't to do with stacks, its just how you're program is laid out... Write out the flow of the program and think about what it is doing.

--i decreases the value of i before it executes that line... so when you call Test(5), it decreases i and calls test again.. Test(4).

Your Console.WriteLi ne() isn't within the if block so will print every time. This means you're program is doing the following:

Expand|Select|Wrap|Line Numbers
  1. Test(5)
  2.   i = 4
  3.     Test(4)
  4.       i = 3
  5.         Test(3)
  6.           i = 2
  7.             Test(2)
  8.             i = 1
  9.               Test(1)
  10.               i = 0
  11.                 Test(0)
  12.                    we stop here, as i is no longer greater than 0. Now start printing
  13.                    print 0 (then return to calling method Test(1))
  14.               print 0
  15.            print 1
  16.          print 2
  17.       print 3
  18.    print 4
  19. print 5 
  20.  
A better layout, is if you write down in a table:

i --i Console.WriteLi ne(i)
5 4 4
4 3 3
3 2 2
2 1 1
1 0 0
0 - 0

then figure out the values each time Test() gets called, then work back up the table to figure out the output...

Hope that helps
Jul 29 '08 #2
lordango
14 New Member
Im just new to programming and your reply really helped.
So its just how the program flows.
i tried to look at other recursion samples and i seemed to have gotten lost.

class Program
{
static int Fibonacci(int x)
{
System.Diagnost ics.Debug.Print ("x = {0}", x);
if (x <= 1)
{
return 1;
}
return Fibonacci(x - 1) + Fibonacci(x - 2);
}

static void Main()
{
System.Diagnost ics.Debug.Print ("Fibonacci no. = {0}", Fibonacci(5));
Console.ReadKey ();
}
}
*************** *************** *********
X=5

Fibonacci(5)
Print 5
Fibonacci(4)
Print 4
Fibonacci(3)
Print 3
Fibonacci(2)
Print 2
Fibonacci(1)
Print 1
--- after this is dont follow anymore :(

does the Fibonacci(x - 2) gets called next?
Jul 30 '08 #3
IanWright
179 New Member
Im just new to programming and your reply really helped.
So its just how the program flows.
i tried to look at other recursion samples and i seemed to have gotten lost.

class Program
{
static int Fibonacci(int x)
{
System.Diagnost ics.Debug.Print ("x = {0}", x);
if (x <= 1)
{
return 1;
}
return Fibonacci(x - 1) + Fibonacci(x - 2);
}

static void Main()
{
System.Diagnost ics.Debug.Print ("Fibonacci no. = {0}", Fibonacci(5));
Console.ReadKey ();
}
}
*************** *************** *********
X=5

Fibonacci(5)
Print 5
Fibonacci(4)
Print 4
Fibonacci(3)
Print 3
Fibonacci(2)
Print 2
Fibonacci(1)
Print 1
--- after this is dont follow anymore :(

does the Fibonacci(x - 2) gets called next?
It's a little more tricky because you have those additions in there. One thing I'd suggest, create a C# application and run it, you can then step through, add watches on variables and find out exactly what its doing.

You're flow is correct so far. You've drilled down recursively into that first Fibonacci(x-1) call, and returned 1. The Fibonacci(x-2) does indeed get called next...

2-2 = 0, so we print 0, and then return 1 based on the logic in the method. Then we add those values for the return

1+1 = 2, so we return 2.

Now we are back to the point where we did Fibonacci(3), so we now need to drill down into the Fibonacci(x-2) for this method aswell...

In doing so, we have called Fibonacci(1) again, so we print 1 and then have then return again... Obviously when we return back up to say our Fibonacci(4) call when we go into Fibonacci(x-2) we're then going to have to drill down into both Fibonacci(x-1) and Fibonacci(x-2) calls again for that function.

Gets quite complicated, I might have even got it wrong as I just did that from looking at it. Create a C# application and try running it, use F11 to step into functions and see what's going on. That's the easiest way with recursion...

Ian
Jul 30 '08 #4
lordango
14 New Member
Heres the debug output:

5
4
3
2
1
0
1
2
1
0
3
2
1
0
1
Fibonacci no. = 8

Im so sorry but i just cant see where did the 8 came from?
Jul 30 '08 #5
IanWright
179 New Member
It's a little more tricky because you have those additions in there. One thing I'd suggest, create a C# application and run it, you can then step through, add watches on variables and find out exactly what its doing.

You're flow is correct so far. You've drilled down recursively into that first Fibonacci(x-1) call, and returned 1. The Fibonacci(x-2) does indeed get called next...

2-2 = 0, so we print 0, and then return 1 based on the logic in the method. Then we add those values for the return

1+1 = 2, so we return 2.

Now we are back to the point where we did Fibonacci(3), so we now need to drill down into the Fibonacci(x-2) for this method aswell...

In doing so, we have called Fibonacci(1) again, so we print 1 and then have then return again... Obviously when we return back up to say our Fibonacci(4) call when we go into Fibonacci(x-2) we're then going to have to drill down into both Fibonacci(x-1) and Fibonacci(x-2) calls again for that function.

Gets quite complicated, I might have even got it wrong as I just did that from looking at it. Create a C# application and try running it, use F11 to step into functions and see what's going on. That's the easiest way with recursion...

Ian
The 8 is because the Fibonacci(x-1) and Fibonacci(x-2) results add together to give 8... so Fibonacci(4) + Fibonacci(3) = 8...
Jul 30 '08 #6
lordango
14 New Member
That would be
(1+2) + (3+2)

is that right?

because i tried to interchange :
Fibonacci(x - 1) + Fibonacci(x - 2)
with
Fibonacci(x - 2) + Fibonacci(x - 1)

and looked at the output.

I figured that the program produces 30 values, (15 values for (x-1) and 15 values for(x-2)) is this correct?

Then it adds the return value f(n-1) + f(n-2) and thats why it returned 8.

its getting clearer now, im still kinda confused about the loop though.
anyway thank you for the post. it really helped.
Jul 30 '08 #7
IanWright
179 New Member
I think that's probably right, I think honestly you should look at a simpler recursion example as this is actually quite difficult to follow.

Look at the procedure for calculating the square root of a number manually through recursion, that is quite a simple example, or alternatively try coming up with a recursive binary search.
Jul 30 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
2522
by: Tim Mohler | last post by:
All - I have a script that provides a web page interface to various system utilities. Once the user has selected the utility and input various parameters, it calls itself with a different method and input value, for instance ping. During the initial call, the output is not buffered, but on the second call, the actually executes the utility, output is buffered until the command completes.
12
2767
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted in modern day applications. Should we readily use it when we can or only when absolutly forced to use it?
12
2493
by: Paul | last post by:
Hi, Global operator new and delete are overloaded and I am using stl map to store pointers, but this code crashes, can some one shed some light??? Compiler: MS VC++ 6.0 STL: Shipped with Visual Studio. #include <malloc.h> #include <map>
2
2600
by: silly | last post by:
/*Thanks again to thos who helped with my 'more hand written integer pow() functions (LONG POST)' query. I needed to write a function to write out integers and after looking at some stuff on the web I felt they look a bit code-heavy so... A) If you think the code attached is reasonable, consider it a donation, if not please lets have your comments!
2
1521
by: Brian Simmons | last post by:
Hi, Long story short: I've got a website built, and we moved it over to the production server, which is an SSL-required (https://...) server. A third party component that I'm using makes use of an <iframe>. Unfortunately they set the SRC attribute to "". This causes Internet Explorer to display a message box dialog warning about this page contains non-secure and secure items, do you wish to display the non-secure items, Y/N?
10
2963
by: Lamefif | last post by:
can anyone explain the output of this function. im having trouble comprehending it void ret_str(char* s) { if(*s != '\0') //{ cout<<*(s) ; ret_str(s+1); //cout<<*(s) ;
6
1928
by: =?Utf-8?B?c2VlbWE=?= | last post by:
1) What will the value of txt be after executing MyFunction? public void Main() { string txt = MyFunction( “12345” ); } public string MyFunction( string str ) { if( str.Length == 1 )
3
1537
by: a | last post by:
After several days struggling, I'm still unable to generate a string automatically *ONE by ONE*. I don't want to create a long array memorizing all the output strings and then traverse this array to print the content out. For example, for studying the frequency of 5-letter words composed of {a,b,c,d,e} in a string, the length of array of (aaaaa, aaaab, ...., caaaa, ..., eeeee) will then be 5*5*5*5*5.
9
1862
by: reachmsn | last post by:
Hi, At the url http://www.python.org/doc/essays/graphs.html there is some code by Guido Van Rossum for computing paths through a graph - I have pasted it below for reference - Let's write a simple function to determine a path between two nodes. It takes a graph and the start and end nodes as arguments. It will return a list of nodes (including the start and end nodes) comprising the path. When no path can be found, it returns None....
0
9636
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10075
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.