Group
Introduction to C++
Objective
1. Initialize three integer variables to store current, previous, and next Fibonacci values.
2. Use a loop that runs 10 times to generate and print the Fibonacci numbers.
3. Update the values accordingly in each iteration to continue the sequence.
4. Display each number in the sequence on the console.
Print the first 10 Fibonacci numbers.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Main function - entry point of the program
int main() {
int n1 = 0, n2 = 1, next; // Initialize first two Fibonacci numbers and a variable for the next number
// Print a message to indicate the start of the Fibonacci sequence
cout << "The first 10 Fibonacci numbers are: ";
// Loop to print the first 10 Fibonacci numbers
for (int i = 1; i <= 10; ++i) {
cout << n1 << " "; // Print the current Fibonacci number
next = n1 + n2; // Calculate the next Fibonacci number
n1 = n2; // Move n2 to n1 for the next iteration
n2 = next; // Assign the new calculated value to n2
}
cout << endl; // Print a newline at the end
return 0; // Return 0 to indicate successful execution
}
Output
The first 10 Fibonacci numbers are: 0 1 1 2 3 5 8 13 21 34