create a function to calculate the sum of any n numbers c++ code example

Example 1: c++ sum of all numbers up to a number

// Method 1: Mathematical -> Sum up numbers from 1 to n 
int sum(int n){
	return (n * (n+1)) / 2;
}

// Method 2: Using a for-loop -> Sum up numbers from 1 to n 
int sum(int n){
	int tempSum = 0; 
  	for (int i = n; i > 0; i--){
     	tempSum += i;  
    }
  	return tempSum; 
}

// Method 3: Using recursion -> Sum up numbers from 1 to n 
int sum(int n){
	return n > 0 ? n + sum(n-1) : 0; 
}

Example 2: how to sum all numbers under a given number c++

#include <iostream>
#include <math.h>
// "#include <math.h> isn't needed.
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	// Sum of numbers in a group under a given number.
	cout << "Insert four numbers:" << endl;
	// In this case the numbers I chose to use are four but you can use how many you want.
	float a, b, c, d;
	cin >> a >> b >> c >> d;
	float aa, bb, cc, dd;
	// The second set of variables must have the same number of variables of the numbers
	// you want to sum.
	if(a < 8){
	// In this case "n" is replaced by 8, but, again, you can use any number you prefer.
		aa = a;
		if(b < 8){
			bb = b;
			if(c < 8){
				cc = c;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			} else {
				cc = 0;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			}
		} else {
			bb = 0;
			if(c < 8){
				cc = c;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			} else {
				cc = 0;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			}
		}
	} else {
		aa = 0;
		if(b < 8){
			bb = b;
			if(c < 8){
				cc = c;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			} else {
				cc = 0;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			}
		} else {
			bb = 0;
			if(c < 8){
				cc = c;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			} else {
				cc = 0;
				if(d < 8){
					dd = d;
				} else {
					dd = 0;
				}
			}
		}
	}
	cout << endl << "Sum of the numbers lower than n (8): " << aa+bb+cc+dd << endl;
	// Basically this associates each number to a variable of the second group and
	// then, through if, it sees which numbers are under n.
	// If they are under n the second variable is given the same numeric value as
	// its respective number, if not its value is equal to 0.
	// It then sums the variables together.
	// To have more/less numbers you add the respective variables, then make two
	// cases where the number is higher or lower than n. Then, you copy-paste
	// the two if chains underneath.
	return 0;
}

Tags:

Cpp Example