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// 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// 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//1
2 int n = 12345, sum = 0;
3 while(n) {
4 sum+=n%10;
5 n/=10;
6 }
7 cout << sum; //15
8//2
9 int n = 12345, sum = 0;
10 for (sum = 0; n > 0; sum += n % 10, n /= 10);
11 cout << sum; //15