Here is a small program to clalculate Fibonacci numbers using c++ language. No tampering with the code needed ( only iprovements ! ) just copy and compile with g++ FibonacciNumber.cpp -o FibonacciNumber and run ./FibonacciNumber

#include <iostream>
#include <cstdlib>

void HowMany(int *numbers);
void CalculateFibonacci(int *numbers);

int main() {

int numbers = 0;

HowMany(&numbers);
CalculateFibonacci(&numbers);

return 0;
}


void HowMany(int *numbers)

{
   // use pointers as parameter, not references
   std::cout << "How many Fibonacci numbers would you like to calculate? ";
   std::cin >> *numbers;
   if ((!std::cin.good()) || ( *numbers <= 1 ||  ( *numbers >= 48 )))

   {
      printf("Invalid number entered ! I calculate only more than 0 or less then 48 Fibonacci numbers !! \n");
      exit(1);
   }

}

void CalculateFibonacci(int *numbers) 
{
	int i = 0;

	unsigned long a = 1;
	unsigned long b = 0;

	unsigned long fibonacci_number = 0;

	while(i < *numbers) {
		b= fibonacci_number;

		fibonacci_number = a + b;
		std::cout << "Fibonacci number: " << i+1 << ". " << fibonacci_number << "\n";

		a = b;
		i++;
	}
	std::cout << std::endl;
}

OUTPUT:

./FibonacciNumber
How many Fibonacci numbers would you like to calculate? 30
Fibonacci number: 1. 1
Fibonacci number: 2. 1
Fibonacci number: 3. 2
Fibonacci number: 4. 3
Fibonacci number: 5. 5
Fibonacci number: 6. 8
Fibonacci number: 7. 13
Fibonacci number: 8. 21
Fibonacci number: 9. 34
Fibonacci number: 10. 55
Fibonacci number: 11. 89
Fibonacci number: 12. 144
Fibonacci number: 13. 233
Fibonacci number: 14. 377
Fibonacci number: 15. 610
Fibonacci number: 16. 987
Fibonacci number: 17. 1597
Fibonacci number: 18. 2584
Fibonacci number: 19. 4181
Fibonacci number: 20. 6765
Fibonacci number: 21. 10946
Fibonacci number: 22. 17711
Fibonacci number: 23. 28657
Fibonacci number: 24. 46368
Fibonacci number: 25. 75025
Fibonacci number: 26. 121393
Fibonacci number: 27. 196418
Fibonacci number: 28. 317811
Fibonacci number: 29. 514229
Fibonacci number: 30. 832040



Free Linux eBooks

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Linux Online Training

Learn to run Linux servers and prepare for LPI certification with Linux Academy. 104 available video lessons with PDF course notes with your own server!

Go to top