Tutorialspoint
Problem
Solution
Submissions

Print Fibonacci Series up to N Terms

Certification: Basic Level Accuracy: 80.49% Submissions: 41 Points: 10

Write a Python program that generates the Fibonacci sequence up to N terms.

Example 1
  • Input: N = 7
  • Output: 0, 1, 1, 2, 3, 5, 8
  • Explanation:
    • Step 1: Initialize the first two terms of the Fibonacci sequence as 0 and 1.
    • Step 2: Generate subsequent terms by adding the two preceding terms.
    • Step 3: Term 1: 0 (by definition)
    • Step 4: Term 2: 1 (by definition)
    • Step 5: Term 3: 0 + 1 = 1
    • Step 6: Term 4: 1 + 1 = 2
    • Step 7: Term 5: 1 + 2 = 3
    • Step 8: Term 6: 2 + 3 = 5
    • Step 9: Term 7: 3 + 5 = 8
    • Step 10: Return the sequence with N = 7 terms: 0, 1, 1, 2, 3, 5, 8
Example 2
  • Input: N = 2
  • Output: 0, 1
  • Explanation:
    • Step 1: Initialize the first two terms of the Fibonacci sequence as 0 and 1.
    • Step 2: For N = 2, we only need the first two terms.
    • Step 3: Return the sequence with N = 2 terms: 0, 1
Constraints
  • 1 ≤ N ≤ 10^3
  • Time Complexity: O(N) where N is the number of terms in the sequence
  • Space Complexity: O(N) to store the sequence
StringsNumberShopifyAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Initialize sequence with [0, 1]
  • Iterate and sum last two numbers to generate next term

The following are the steps to print the Fibonacci series up to n terms:

  • Define the function fibonacci_sequence(n).
  • Handle edge cases for n <= 0, n == 1, and n == 2.
  • Use a loop to generate Fibonacci numbers and store them in a list.
  • Return the list and print the result.

Submitted Code :