Group
Introduction to C++
Objective
1. Declare an integer variable to store the user's input (N) and another to store the sum.
2. Ask the user to enter a positive integer.
3. Use a loop to iterate from 1 to N and add each number to the sum.
4. Display the final result.
Sum the first N natural numbers.
Example C++ Exercise
Show C++ Code
#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
}
Output
Enter a positive integer: 5
The sum of the first 5 natural numbers is: 15