1int x, s = 0;
2 cout << "Enter the number : ";
3 cin >> x;
4 while (x != 0) {
5 s = s + x % 10;
6 x = x / 10;
7 }
1// sum the digits of an integer
2int getSum(long long n) {
3 int sum = 0;
4 int m = n;
5 while(n > 0) {
6 m = n % 10;
7 sum = sum + m;
8 n = n / 10;
9 }
10 return sum;
11}
1// Method 1: Mathematical -> Sum up numbers from 1 to n
2int sum(int n){
3 return (n * (n+1)) / 2;
4}
5
6// Method 2: Using a for-loop -> Sum up numbers from 1 to n
7int sum(int n){
8 int tempSum = 0;
9 for (int i = n; i > 0; i--){
10 tempSum += i;
11 }
12 return tempSum;
13}
14
15// Method 3: Using recursion -> Sum up numbers from 1 to n
16int sum(int n){
17 return n > 0 ? n + sum(n-1) : 0;
18}
1#include <iostream>
2#include <math.h>
3// "#include <math.h> isn't needed.
4using namespace std;
5/* run this program using the console pauser or add your own getch, system("pause") or input loop */
6
7int main(int argc, char** argv) {
8 // Sum of numbers in a group under a given number.
9 cout << "Insert four numbers:" << endl;
10 // In this case the numbers I chose to use are four but you can use how many you want.
11 float a, b, c, d;
12 cin >> a >> b >> c >> d;
13 float aa, bb, cc, dd;
14 // The second set of variables must have the same number of variables of the numbers
15 // you want to sum.
16 if(a < 8){
17 // In this case "n" is replaced by 8, but, again, you can use any number you prefer.
18 aa = a;
19 if(b < 8){
20 bb = b;
21 if(c < 8){
22 cc = c;
23 if(d < 8){
24 dd = d;
25 } else {
26 dd = 0;
27 }
28 } else {
29 cc = 0;
30 if(d < 8){
31 dd = d;
32 } else {
33 dd = 0;
34 }
35 }
36 } else {
37 bb = 0;
38 if(c < 8){
39 cc = c;
40 if(d < 8){
41 dd = d;
42 } else {
43 dd = 0;
44 }
45 } else {
46 cc = 0;
47 if(d < 8){
48 dd = d;
49 } else {
50 dd = 0;
51 }
52 }
53 }
54 } else {
55 aa = 0;
56 if(b < 8){
57 bb = b;
58 if(c < 8){
59 cc = c;
60 if(d < 8){
61 dd = d;
62 } else {
63 dd = 0;
64 }
65 } else {
66 cc = 0;
67 if(d < 8){
68 dd = d;
69 } else {
70 dd = 0;
71 }
72 }
73 } else {
74 bb = 0;
75 if(c < 8){
76 cc = c;
77 if(d < 8){
78 dd = d;
79 } else {
80 dd = 0;
81 }
82 } else {
83 cc = 0;
84 if(d < 8){
85 dd = d;
86 } else {
87 dd = 0;
88 }
89 }
90 }
91 }
92 cout << endl << "Sum of the numbers lower than n (8): " << aa+bb+cc+dd << endl;
93 // Basically this associates each number to a variable of the second group and
94 // then, through if, it sees which numbers are under n.
95 // If they are under n the second variable is given the same numeric value as
96 // its respective number, if not its value is equal to 0.
97 // It then sums the variables together.
98 // To have more/less numbers you add the respective variables, then make two
99 // cases where the number is higher or lower than n. Then, you copy-paste
100 // the two if chains underneath.
101 return 0;
102}