DEV Community

key
key

Posted on

How to calculate digit sum by C++

Basic Approach

Let's take 2026 as an example.

  • 2026 can be written as 2020 + 6.
  • Since 2020 is divisible by 10, dividing 2026 by 10 leaves a remainder of 6.
  • Using this property, we can extract the digit in the ones place.


Here is the code example:

#include <bits/stdc++.h>
using namespace std;

int main(){
  int digit = 2026;

  // digit = 2026 (2020 + 6)
  cout << "ones place: " << digit % 10 << endl;

  digit /= 10; // digit = 202 (200 + 2)
  cout << "tens place: " << digit % 10 << endl;

  digit /=10; // digit = 20 (20 + 0)
  cout << "hundreds place: " << digit % 10 << endl;

  digit /=10; // digit = 2
  cout << "thousands place: " << digit % 10 << endl;
}
Enter fullscreen mode Exit fullscreen mode


Output:

ones place: 6
tens place: 2
hundreds place: 0
thousands place: 2
Enter fullscreen mode Exit fullscreen mode

Streamlined Implementation

We can simplify this step using a while loop. Since each division by 10 removes the last digit, the number will eventually become 0.

#include <bits/stdc++.h>
using namespace std;

int main(){
  int digit = 2026;

  while (digit > 0) {
    cout << digit % 10 << endl;
    digit /= 10;
  }
}
Enter fullscreen mode Exit fullscreen mode


Output:

6
2
0
2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)