Click here to Skip to main content
15,512,632 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How is this code calculated?



using System;
public class hi
{
 static void Main(string[] a)
 {
   Console.WriteLine ( g(4)+g(5)+","+g(6));
 }
  static  int g( int k)
 {
     if((k==1)||(k==2))
     return 1;
     else
     return g(k-1)+g(k-2);
 }
}


What I have tried:

I think it's a recursive function
But how is it calculated?

(4-1)+(5-1)=9
?,,,,,?????
Posted
Updated 6-Feb-22 5:40am
v3

It is indeed recursive:
static  int g( int k)
   {
...
   return g(k-1)+g(k-2);
   }
The call to g inside g makes it direct recursion (indirect recursion is harder to spot, as it involved foo calling bar which calls foo.

Look at the code, and think about what happens when you call it with a specific number, start small:
For 1 we know that because it's a special case:
g(1) => 1

For 2, a special case again:
g(2) => 1

And try 3:
g(3) => return g(2) + g(1) => 1 + 1 => 2

We know g(2) and g(1) so we can use those values.
And 4:
C#
g(4) => g(3) + g(2) => 2 + 1 => 3

And 5:
C#
g(5) => g(4) + g(3) => 3 + 2 => 5

Finally 6:
C#
g(6) => g(5) + g(4) => 5 + 3 => 8

So this code:
C#
Console.WriteLine ( g(4)+g(5)+","+g(6));

Is just
C#
Console.WriteLine ( 3+5+","+8);
will give you 8,8
Make sense?
 
Share this answer
 
Comments
George Swan 6-Feb-22 17:34pm    
It is simply producing a Fibonacci sequence, in which each number is the sum of the two previous numbers. 1, 1, 2, 3, 5, 8, 13, 21, 34 etc
Quote:
I think it's a recursive function
But how is it calculated?

There is an easy way to know, use the debugger ans watch your code performing step by step.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

Debugging C# Code in Visual Studio - YouTube[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
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