sum of all positive integers , sum of negative integers in c++
Answers
Answered by
1
To understand this example, you should have the knowledge of 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 = 1275
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 = 1275
Similar questions
Business Studies,
7 months ago
English,
7 months ago
Physics,
1 year ago
Environmental Sciences,
1 year ago