Write a C++ program that computes the sum of the first N natural numbers, where N is input by the user.
Input and Output Examples
- Input: 5
Output: The sum of the first 5 natural numbers is 15. - Input: 10
Output: The sum of the first 10 natural numbers is 55.
Algorithm to calculate the sum of natural numbers:
- Start the Program: Include necessary headers and declare the use of the standard namespace.
- Prompt for Input: Ask the user to enter a positive integer N.
- Read the Input: Store the input value in a variable.
- Calculate the Sum: Use a for loop to start calculating the sum of the first N natural numbers from i = 1 to N.
- Display the Output: Print the calculated sum.
- End the Program: Finish execution cleanly.
Method 1: Using a Loop
This method uses a for loop to iterate from 1 to N, accumulating the sum of these numbers.
cpp
#include <iostream>
using namespace std;
int main() {
int n, sum = 0; // Declare variables for the number of terms and the sum.
// Take input va;ues
cout << "Enter a positive integer: ";
cin >> n; // Read the integer value.
// Calculate the sum using a for loop
for (int i = 1; i <= n; ++i) {
sum += i; // Add each number to sum.
}
cout << "The sum of the first " << n << " natural numbers is " << sum << "." << endl; // Display the sum.
return 0; // End the program successfully.
}
Method 2: Using the Formula
For a more efficient calculation, use the mathematical formula for the sum of the first N natural numbers: (N×(N+1) ) / 2.
cpp
#include <iostream>
using namespace std;
int main() {
int n, sum; // Declare variables for the number of terms and the sum.
cout << "Enter a positive integer: ";
cin >> n;
// Calculate the sum using the formula
sum = n * (n + 1) / 2; // Apply the formula to calculate the sum.
cout << "The sum of the first " << n << " natural numbers is " << sum << "." << endl;
return 0;
}