Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to print the following febonnaci series. 0 1 1 2 3 5 8 13 21 34 upto n times

C++ Code Example — Series Programs

ADVERTISEMENT

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

  1. Initialize variables: a = -1 and b = 1.
  2. Read the number of terms n.
  3. Run a loop i from 1 to n.
  4. Calculate the next term: c = a + b.
  5. Print c.
  6. Shift variables forward: a = b and b = 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)
ADVERTISEMENT