WAP to print the following febonnaci series. 0 1 1 2 3 5 8 13 21 34 upto n times
Objective
Write a C++ program to print the Fibonacci series: 0, 1, 1, 2, 3, 5, 8 ... N.
Algorithm / Approach
- Initialize variables:
a = -1andb = 1. - Read the number of terms
n. - Run a loop
ifrom 1 ton. - Calculate the next term:
c = a + b. - Print
c. - Shift variables forward:
a = bandb = c.
main.cpp
#include<iostream>
using namespace std;
int main() {
int n,a = -1, b = 1,c;
cout<<"Enter the Value for N : ";
cin>>n;
for(int i = 1; i<=n; i++) {
c = a+b;
cout<< c<<" ";
a = b;
b = c;
}
cout<< endl;
return 0;
}
Expected Output
Enter the Value for N : 9 0 1 1 2 3 5 8 13 21
Explanation of the Program
- The Fibonacci series is a sequence where the next number is found by adding up the two numbers before it.
- By initializing the base numbers to -1 and 1, the first calculation becomes (-1 + 1 = 0), matching the mathematical start of the sequence. Then we shift the variables forward so the next calculation uses (1 + 0 = 1).
Complexity
Time Complexity
O(n)
Space Complexity
O(1)