# C++ code help (Optimizations, issue)

Here is my code: pastebin.com/Tng93eJA

My issues are at the bottom of my code(yes I am trying to make you read it lol). I am a beginner so any solutions one of you have, can you please state why you propose that solution? I think I have a solution for problem 1, but it adds length to my already seemingly lengthy code, so I am waiting for a possible fix to problem 2 and/or a solution from one of you. As far as I know, my code works fine. I have a version of this running but it's not the exact version in pastebin(the one in pastebin is what I would add to the stuff on my Raspberry Pi. My Pi has this code just without the if and else if statements).  Thanks in advance for taking time out of your day/night to look at this.

The easiest way to calculate the Fibonacci sequence is to use recursion.  If you are just starting to learn how to code, you may not know what recursion is so I will briefly describe it.  Recursion is where you define a method or function and within that method or function you call yourself--the defined method--with different values.  When using recursion you have to be careful that there is an eventual exit condition.  Otherwise, you will end up with a stack overflow condition, causing your program to crash.  Recursion is generally used to calculate mathematical series like Fibonacci or factorials and to traverse data structures like binary trees.

You certainly can calculate the Fibonacci sequence using loops, but recursion will make your code much more concise.  Recursion can be a little tricky to get the hang of, especially when you are first learning it.  But the key thing to remember with recursion is that you must complete everything you start.  So if you call yourself ten times, the remaining code after the call to yourself has to be executed ten times, once for each recursive step, plus one additional time for the initial method invocation.

Here is how you solve the Fibonacci sequence using recursion:

http://pastebin.com/cpnKLTK7

Ah recursion. I can't believe I didn't think if that. I've been working on a version with a bunch of if/else if statements. I think you can guess without looking at it that it's a nightmare. This definitely clears up both of my issues. It seems this is in a C format, I'll work on a C++ version. I know both versions will work fine but I'm learning C++ so I'll take it wherever I can get it. Thanks for the response, it helped a bunch!