for loop adding numbers c++ code example
Example 1: c++ sum of all numbers up to a number
int sum(int n){
return (n * (n+1)) / 2;
}
int sum(int n){
int tempSum = 0;
for (int i = n; i > 0; i--){
tempSum += i;
}
return tempSum;
}
int sum(int n){
return n > 0 ? n + sum(n-1) : 0;
}
Example 2: how to add numbers in for loop c++
#include <iostream>
int main() {
int n = 0;
int sum = 0;
std::cout << "Please enter and integer: ";
std::cin >> n;
while (n < 0 ) {
std::cout <<"Please enter positive integer only.\n";
std::cout << "Please enter and integer: ";
std::cin >> n;
}
for (int i = 0; i < n ; i++) {
std::cout << i << "\n";
sum +=i
}
std::cout << "Sum of odd numbers is " << sum <<".\n";
}