Author: Theodore Odeluga
The source files for this project can be downloaded from here
Sometimes, you don't want to build anything, you just want to play around with code. It's just as well then that the insights gained through experimenting in this way are often invaluable.
Simply "trying stuff out" develops your skill as a coder, your general ability to think in abstract "out of the box" terms and improves your approach to well, problem solving.In this experimental spirit, I thought I'd also use a different language for a change. Although it's perfectly feasible to do everything we're going to do here using JavaScript (running the program on the command line with Node.js), C++ is a great choice for "pure" programming.
While it's getting a bit long in the tooth now (Bjarne Stroustrup, its creator released the first version back in 1985) and is gradually being replaced by newer compiled languages such as Google's Go, C++ remains a powerful tool and its standards a benchmark for building fast, efficient applications. Indeed, it's development is still going strong, with the release of C++ 20 in December last year (along with the fact that Go itself was partially written in C++).
We therefore have a good technology for the task at hand, so let's get on with using it.
To demonstrate logical problem solving, we need an example complex enough to illustrate useful techniques but not so difficult that we defeat the objective - which of course is to teach the important fundamentals.
How about an implementation of the Fibonacci sequence? It's not the most original idea, but while there are several examples of solutions for this all over the web, they don't all follow the same methodology (just a basic principle) and there's nothing stopping us from coming up with our own take on the subject, so let's begin.
The First point of logical problem solving is to first ensure we understand the problem. Sounds like an obvious point, but we've all either made the mistake ourselves or know someone who answered an exam question incorrectly because they misunderstood that question (from not reading it properly). So before we go any further, we need to make sure we're on the right track.
Our task is this: Essentially, we need to give the computer a way to create a sequence of numbers where every third number is a sum of the previous two.
The second point about solving a problem is to check if we know anything in advance about the potential solution (is the answer hidden in the question so to speak?).
Nothing springs to mind except the fact that it so happens the first 3 numbers in the Fibonacci sequence are also the first 3 numbers. This is an equally banal and obvious point but it gives us a head start.
What do we have so far?
1. The Fibonacci sequence is made up of 3 numbers - first number, second number, and a third (the sum of the previous two).
2. The first 3 numbers in the sequence are the first 3 numbers.
3. We need to store the sum of every previous two numbers in every third number - but the next number after the sum must reflect the pattern of the series (not necessarily follow in sequence).
The trick will be separating the numbers so that the computer doesn't keep incrementing a single value by just adding up everything that's come before.
We can start to do this by thinking of the numbers as the separate "components" of the Fibonacci sequence.
We can simplify things even further and make this clarity more explicit by storing each number in its own dedicated variable.
If we can then provide the computer with the first 3 numbers via these variables, as a kind of "template pattern" (indicating the third is a sum of numbers 1 and 2), we could instruct it to otherwise keep a running count as normal (1,2,3,4 etc.) but do an adding up operation every two numbers.
Now we've got an idea of how this works, let's try it out.
If you don't have a C++ compiler installed, I can recommend the one that comes with the Code Blocks IDE. It's lightweight, easy to use and free. Visual Studio code is also a good choice. This is free from Microsoft.
I used Code Blocks to write the program but I believe it should work with any good up to date C++ compiler.
The method I found particularly useful was to first type everything up in Notepad++ (another free tool), then copy and paste everything from there into Code Blocks to run it.
You can write and run the program in Code Blocks directly of course, but I found it easier to do all my "working out" elsewhere before transferring to the other software.
Let's set up the skeleton of our app. Please bear in mind that this isn't a C++ tutorial per se. If you want to learn more about the language, W3Schools provide an excellent introduction.
Copy and paste the following into your editor.
#include<iostream>
using namespace std;
int fibonacci(int num){
}
int main() {
fibonacci(1);
return 0;
}
The statements at the start of the program essentially allow us to output results to the screen and recieve input from the user. In this case we'll just be outputting results produced by the fibonacci function via it's single parameter 'num'. Both this parameter and the function are integer objects, as per the purpose of the exercise - working with whole numbers.
It's customary to have a 'main' function in C++ programs and this is often used to either run separately defined functions or an apps core code directly. The return statement at the end of main indicates the end of its execution and the numeric value indicates whether the functions execution was successful.
Note that the value in the call to the fibonacci function fibonacci(1); is arbitrary. The value of the parameter here is just for demonstration purposes and it's where you would tell fibonacci() the number of times to repeat.
Just under the line containing the function name and parameter (int fibonacci(int num){ )
type the following.
int i = 0;
int first = 0;
int second = 0;
int sum;
The integer variables first, second and sum will contain the values for the first two numbers and their sum respectively. The integer 'i' will be the iterator for the loop which will cycle through the sequence of the algorithm. The value of the parameter 'num' will determine how many times the sequence will repeat.
After the declaration of int sum; type the following.
first += 1;
second += 2;
sum = first + second;
cout << first << "\n";
cout << second << "\n";
As mentioned earlier, we increment the integer 'first' with a value of 1 then the integer 'second' with a value of 2. The 'sum' variable then stores the sum of these two variables. Afterwards, the result is output to the console.
Type the next block of code just above the last curly brace before the start of int main().
while (i < num) {
first += second;
second += first;
sum = first + second;
cout << first << "\n";
cout << second << "\n";
i++;
}
The While loop increments the value of 'i' for as long as 'i' is less than 'num'. As this is happening, the 'first' variable is incremented by the 'second', and then the the 'second' variable is "chained" back to 'first' by continuing - and reversing - the incrementation operation on the previous line. This is done so as not to break the process. 'Sum' continues to add the two variables together. 'i' effectively forces the process to repeat by adding another iteration to the loop (until it stops once its value is no longer less than that of 'num').
That's the end of the 'fibonacci' function (ensure there are an equal number of closing curly braces as there are opening curly braces).
Place the code for the 'main' function just underneath the 'fibonacci' definition.
int main() {
fibonacci(5);
return 0;
}
If you place this code in Code Blocks then select Build and Run under the Build menu, you should see a series of numeric values in the console following the fibonacci algorithm. The sequence will run a specific number of times producing a range of values depending on the number of iterations specified.
Further Development
There are lots of ways you can go with this. Websites such as the Euler Project provide similar coding challenges to the one outlined here and these puzzles in programming logic are a great way to practice. One book which I have found very useful over the years for learning computer programming problem solving techniques is this is one by Robert Lamey - Logical Problem Solving (Prentice Hall). It's quite an old volume, but is still available. I hope you enjoyed the tutorial and thanks for reading.