The below program will accept the number “n” from the user and calculates the sum of first “n” natural numbers.
For example, if the input provided by the user is 5 then it will calculate the sum of first 5 natural numbers i.e., 1+2+3+4+5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/* Program Name: Program in C++ to find sum of first "n" natural numbers Author: LearnCPPOnline.com */ #include #include "conio.h" using namespace std; void main() { int sum, digit, n; sum = 0; digit = 1; cout << "Enter a number n: "; cin >> n; while(digit <= n) { sum = sum + digit; digit++; } cout << "Sum of first " << n << " natural numbers: " << sum << endl; getch(); } |
Output
1 2 |
Enter a number n: 10 Sum of first 10 natural numbers: 55 |
Note: The above program is written and tested using Microsoft Visual Studio 2008
C++ program to find the sum of 5 numbers using default arguments entha programku answer plz