1. Introduction
Natural numbers are the set of positive integers starting from 1 and extending indefinitely. They play a foundational role in arithmetic and number theory. In this post, we will create a C++ program to find the sum of n natural numbers.
2. Program Overview
The formula to calculate the sum of the first n natural numbers is given by:Sum = n * (n + 1) / 2
Using this formula, our program will:
1. Prompt the user to enter the value of n.
2. Compute the sum of the first n natural numbers.
3. Display the calculated sum.
3. Code Program
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
// Prompting the user for the value of n
cout << "Enter a positive integer: ";
cin >> n;
// Calculating the sum
sum = n * (n + 1) / 2;
// Displaying the result
cout << "The sum of first " << n << " natural numbers is: " << sum;
return 0; // Signify successful program termination
}
Output:
Enter a positive integer: 5 The sum of first 5 natural numbers is: 15
4. Step By Step Explanation
1. Headers and Namespace: We initiate by including the iostream library for input-output operations and specifying the use of the standard namespace.
2. Main Function: The program starts its execution from here. Inside, we declare two integer variables - n to store the user input and sum to store the result.
3. User Input: We utilize cout to prompt the user for input and cin to receive the number.
4. Calculation: Using the formula mentioned above, we quickly compute the sum of the first n natural numbers.
5. Displaying the Result: The sum is then printed out using cout.
6. Program Termination: The program concludes, indicating a successful execution with a return value of 0.
Comments
Post a Comment
Leave Comment