Grupo
Introducción a C++
Ojetivo
1. Declarar una variable entera para almacenar la entrada del usuario (N) y otra para almacenar la suma.
2. Pedir al usuario que introduzca un entero positivo.
3. Usar un bucle para iterar de 1 a N y sumar cada número a la suma.
4. Mostrar el resultado final.
Suma los primeros N números naturales.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the iostream library to handle input and output
using namespace std; // Use the standard namespace
// Main function - the starting point of the program
int main() {
int N, sum = 0; // Declare an integer N for user input and sum initialized to 0
// Prompt the user to enter a positive number
cout << "Enter a positive integer: ";
cin >> N; // Read user input and store it in variable N
// Use a for loop to calculate the sum from 1 to N
for (int i = 1; i <= N; ++i) {
sum += i; // Add each number to the total sum
}
// Display the result of the summation
cout << "The sum of the first " << N << " natural numbers is: " << sum << endl;
return 0; // Return 0 to indicate that the program ended successfully
}
Salida
Enter a positive integer: 5
The sum of the first 5 natural numbers is: 15
Comparte este ejercicio C++