Solution for q3.cpp

This program will print out the fibonacci series of a number given by the user. In order to make this program better, it should print out all the fibonnacci values until geting the one the user entered. Here is an example:

fibonacci of 10:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55
the 10th value of your number in the fibonacci series is: 55.

In order to do this, we will need 4 variables:

  • long a=1;
  • long b=0;
  • long fibo;
  • long value;

For this program to work, frist, lets remember how fibonacci works… Solution for q3.cpp photo by: http://en.wikipedia.org/wiki/Recurrence_relation

In order to follow this mathematical formula, we will use a “for” loop, that sums our variables a and b (fibo= a+b) after giving “a” the value of “b” and “b” the value of “fibo” for many times. 

Here is how the loop should look:

for(int i=0; i<value; i++){

  fibo=a+b;

  a=b;

  b=fibo;

  cout<<fibo<<endl;

 }

Remember that the variable “i” in the loop, will work until its equal  or bigger than the initian value. 

The (cout<<fibo<<endl;) part inside the loop, is created in order to print out all values of the fibonacci series until it gets the one given by the user.

After creating this loop, you only have to print out “fibo” which will work as your result.

Here is a picture of how the program should run:

CC BY 4.0 Solution for q3.cpp by carlos green is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.