Total members 11890 |It is currently Fri Apr 19, 2024 4:58 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





Implementing fibonacci sequence problem using iterations
cpp code
#include <iostream>
#include <iomanip>
using namespace std;

//function declaration
double fibonacci(unsigned int n);

int main()
{
int n;

cout << "Enter a number: ";
cin >> n;

//An 'If' condition to prevent the user from entering -ve integers
if (n<0){
cout << "Please Enter a positive integer!" << endl;
return 0;
}
else
cout << "The fibonacci number is " << fibonacci(n) << endl;

cout << "The fibonacci sequence is as follows:" << endl;

//Print Table Heading
cout << setw(10) << "n" << setw(10) << " | " << setw(10) << "F(n)" << endl;
cout << "-----------------------------------------" << endl;

//A Loop to print fibonacci numbers until 'n' in a tabular form
for(int i=0;i<=n;i++)
cout << setw(10) << i << setw(10) << " | " << setw(10) << fibonacci(i) << endl;

return 0;
}

//function definition
double fibonacci(unsigned int n)
{
//n_minus_1 represents what's supposed to be F(n-1)
//n_minus_2 represents what's supposed to be F(n-2)
//sum represents F(n) which equals F(n-1)+F(n-2)
double n_minus_1=0,n_minus_2=1,sum;


switch(n)
{
//if n=0 then F(n)=0
case 0:
return 0;

//if n=1 then F(n)=1
case 1:
return 1;

//otherwise the sum (i.e F(n)) is equal to (n_minus_1)+(n_minus_2) (i.e F(n-1)+F(n-2)
//the counter keeps on moving the variables areound 'n' times
//so that on each time F(n-2) becomes equal to F(n-1) and F(n-1) becomes equal to F(n)
//and F(n) is reevaluated each time in the loop
default:
for(int counter=0;counter<n;counter++)
{
sum=n_minus_1+n_minus_2;
n_minus_2=n_minus_1;
n_minus_1=sum ;
}
}
return sum;
}




_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 1 post ] 

  Related Posts  to : Implementing fibonacci sequence problem using iterations
 solving fibonacci sequence recursively     -  
 Fibonacci vs factorial     -  
 Fibonacci iterative     -  
 Sequence Generator JPA     -  
 add sequence of decimal numbers     -  
 Invalid unicode sequence error ("u")     -  
 Implementing synchronization in C++ with threads     -  
 When to choose C++ for implementing your project and Why     -  
 JButtons implementing an Action     -  
 Data missing when implementing 3DES using DES     -  



Topic Tags

C++ Algorithms
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com