Beginner C/C++ Exercises

Fibonacci Sequence

Each Fibonacci number is the sum of the two values before it.

What is Fibonacci Sequence?

Each Fibonacci number is the sum of the two values before it.

Generate the first ten Fibonacci numbers.

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

C
Run code →
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("");
}
Expected output
0 1 1 2 3 5 8 13 21 34
C++
Run code →
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';
}
Expected output
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.