Fibonacci Sequence
Generate the first ten Fibonacci numbers.
What is Fibonacci Sequence?
Each Fibonacci number is the sum of the two values before it.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
int first = 0, second = 1;
for (int i = 0; i < 10; ++i) {
printf("%s%d", i ? " " : "", first);
// Advance the pair without storing the whole sequence.
int next = first + second; first = second; second = next;
}
puts("");
}
0 1 1 2 3 5 8 13 21 34
C++
main.cpp
#include <iostream>
int main() {
int first = 0, second = 1;
for (int i = 0; i < 10; ++i) {
if (i) std::cout << ' ';
std::cout << first;
// Advance the pair without storing the whole sequence.
int next = first + second; first = second; second = next;
}
std::cout << '\n';
}
0 1 1 2 3 5 8 13 21 34
C and C++ comparison
Two state variables are sufficient because each iteration only needs the previous pair.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges