Can someone help me understand following code step by step? In this program sumDigits() calculates the sum of all the digits in an integer

void setup() {

Serial.begin(9600);

Serial.println(sumDigits(0)); // Should be 0
Serial.println(sumDigits(2)); // Should be 2
Serial.println(sumDigits(28)); // Should be 10
Serial.println(sumDigits(504)); // Should be 9
Serial.println(sumDigits(2048)); // Should be 14
Serial.println(sumDigits(32767)); // Should be 25
}

void loop() {
// Do nothing
}

int sumDigits(int x) {

// Define a local variable
int sum = 0;

// Find how many times 10000 goes into our number and add that
// to our sum. Multiply the number of times 10000 goes into our
// number by 10000 and subtract that from our number.
sum += x / 10000;
x -= (x / 10000) * 10000;

// Repeat the same thing for 1000.
sum += x / 1000;
x -= (x / 1000) * 1000;

// Repeat the same thing for 100.
sum += x / 100;
x -= (x / 100) * 100;

// Repeat the same thing for 10.
sum += x / 10;
x -= (x / 10) * 10;

// No need for any fancy math. The remaining value in our x
// variable should be the value of the ones digit.
sum += x;

return sum;
}

Hi,
to get a good help, read the topic :

and put your code properly formatted inside the tags</>.

What does the code actually do? (It might be wrong).

the program is composed of 3 sub-functions

  • setup()
  • loop()
  • sumDigits()

setup() and loop() are required. setup() is called once and loop() repeatedly.

loop() doesn't do anything.

setup() initializes the serial interface to 9600 bits-per-second and prints the return value of sumDigits() with various arguments

sumDigits() returns the sum of the decimal digits of it argument. it starts with the thousands digit by doing integer division by 1000 and setting sum to that value. it then subtracts that the thousands value of the argument to determines the values of the hundreds digit and adds that to sum, and so on...

so the result of 12 is 3, 123, is 6, 1234 is 10, 12345 is 15

This code adds the most significant digit to the least significant digit.
It's backwards and myopic though.
The standard approach is to get the least significant digit by modulating with 10 as the modulus.
Then to accumulate that digit.
Then to remove that digit with integer division by 10.

The code you provided does it, but from the other end, and will only work for number up to 5 digits. It does many times the necessary operations and has a fixed scope. Generally, it is bad code.

But I don't want to end on a negative note, so here is a quality example of code that does the same thing correctly: C++ Program to Sum the digits of a given number (tutorialspoint.com)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.