so Im new to the world of programming and thought Id pick up a book to start learning. I bought A Players Guide to C# 3rd Edition and one of the little homework assignments it gives you has me pretty stumped. I was debugging it step by step to help me understand, but the flow of the program makes no sense to me. Here it is.
static void Main(string[] args)
{
for (int index = 1; index <= 10; index++)
{
Console.WriteLine(Fibonacci(index));
}
Console.ReadKey();
}
/// <summary>
/// Returns a number from the Fibonacci sequence, starting at 1.
/// Note that this implementation is not very optimized, and can
/// take a very long time if you're looking up large numbers.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
static ulong Fibonacci(int number)
{
if (number == 1) { return 1; }
if (number == 2) { return 1; }
return Fibonacci(number - 1) + Fibonacci(number - 2);
}
the first two times it runs through the for loop it prints out '1' and '1' because the first time through the index is '1' making that first if statement true and the second time through the index is '2' making the second if statement true. But when it runs a 3rd time and the index turns to 3 it goes to that return statement, and if my math is right (3-1) + (3-2) equates to 3, which makes sense right. So I expect it to break from the method return 3 and write that to the Console window, but it doesnt. Instead it runs through the method again this time saying the value of the number is 2.(ok??) well at least it should stop at that 2nd if statement and reprint '1' again. Nope it ignores that line hits the return statement again. What the hell is going on? Please explain this logic.