Fibonacci sequence
Generate the first 10 Fibonacci numbers, starting with 0 and 1.
Course progress
Problem 2 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
count = 10
Expected output
0 1 1 2 3 5 8 13 21 34
What is happening?
Begin with 0 and 1. Every later value is the sum of the previous two, so the sequence continues 1, 2, 3, 5, and so on until ten values have been produced.
Solution strategy
Build the right mental model
Keep only the previous two values. Print the current value, then advance both variables together.
Core concepts
iteration · state
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for fibonacci-sequence
using System;
class Program
{
static void Main()
{
int previous = 0;
int current = 1;
for (int i = 0; i < 10; i++)
{
Console.Write(previous + (i == 9 ? "" : " "));
int next = previous + current;
previous = current;
current = next;
}
}
}Knowledge check
Questions students often ask
What is the main idea behind fibonacci sequence?
Keep only the previous two values. Print the current value, then advance both variables together.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.