Grupo
Introducción a C++
Ojetivo
1. Inicialice tres variables enteras para almacenar los valores de Fibonacci actual, anterior y siguiente.
2. Use un bucle que se ejecute 10 veces para generar e imprimir los números de Fibonacci.
3. Actualice los valores según corresponda en cada iteración para continuar la secuencia.
4. Muestre cada número de la secuencia en la consola.
Imprima los primeros 10 números de Fibonacci.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
The first 10 Fibonacci numbers are: 0 1 1 2 3 5 8 13 21 34
Comparte este ejercicio C++