Adding Natural Numbers in C++

Exercise:

Write a C++ program to add the number of natural number you want to add, starting from 1.

Click Here to View the Solution
#include <iostream>
using namespace std;
int main()
{
    int i, sum = 0;
    cout << "Enter any integer having positive value:\n ";
    cin >> i;
    for (int j = 1; j <= i; ++j)
    {
        sum += j;
    }
    cout << "Sum of first " << i << " natural numbers is "<< sum;
    return 0;
}
Click Here to View the Output:
Enter any integer having positive value:
  7
 Sum of first 7 natural numbers is 28
Click Here to View the Explanation:
  • All positive integers are natural numbers.
  • A number i is inserted by the user and the compiler gives an output of the first i numbers. The number entered by the user is always considered to be a positive number.
  • For example, if -3 is added, the screen will display: The sum of first -3 numbers is 0. The sum in case of the insertion of any negative number is considered and printed on screen as 0.
  • The sum of first i natural numbers can also be found using a recursion.
%d bloggers like this: