write a program in c++ to find the sum of digits of a given number. code example

Example 1: sum of digits in c++

int x, s = 0;
   cout << "Enter the number : ";
   cin >> x;
   while (x != 0) {
      s = s + x % 10;
      x = x / 10;
   }

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