C++ Program To Calculate Sum Of Natural Numbers - Programiz
To understand this example, you should have the knowledge of the following C++ programming topics:
- C++ for Loop
Positive integers 1, 2, 3, 4... are known as natural numbers.
This program takes a positive integer from user (suppose user entered n ) then, this program displays the value of 1 + 2 + 3 + ... + n.
Example: Sum of Natural Numbers using loop
#include <iostream> using namespace std; int main() { int n, sum = 0; cout << "Enter a positive integer: "; cin >> n; for (int i = 1; i <= n; ++i) { sum += i; } cout << "Sum = " << sum; return 0; }Output
Enter a positive integer: 50 Sum = 1275This program assumes that user always enters positive number.
If user enters negative number, Sum = 0 is displayed and program is terminated.
This program can also be done using recursion. Check out this article for calculating sum of natural numbers using recursion.
Từ khóa » C++ 1 2
-
C++ Why Does ((1 / 2) * 2) Return 0 [duplicate] - Stack Overflow
-
1%2 - Modulus Question - C++ Forum
-
C++ : Calculate The Series (1) + (1+2) + … + (1+2+3+...+n)
-
C++ Basics - C++ Programming Tutorial
-
Is .5 Equal To 1/2 In The C Language? - Quora
-
Modulo Operator (%) In C/C++ With Examples - GeeksforGeeks
-
A Short Introduction To Computer Programming, Using C++
-
BASICs Of C/C++ Programming
-
10 Common Programming Mistakes In C++ 1 - UCR CS
-
4. Basic Declarations And Expressions - Practical C++ Programming ...
-
Plus One - LeetCode
-
1/2 Should Not Equal Zero - Musing Mortoray
-
C++ Program To Find Nth Term Of The Series 1, 1, 2, 6, 24…
-
[PDF] Some Practice Problems For The C++ Exam And Solutions For The ...