user3345371
user3345371

Reputation: 11

C Newbie: Split a number into pairs and sum up

I'm teaching myself C (not C++, not yet). After searching the web in general and SO specifically for a couple of hours, I'm still stumped on how to do something fairly basic. Split a number into pairs, then sum those pairs. Something like:

1234567890 --> 12 + 34 + 56 +78 + 90 = 270

I tried treating the number as a string, putting it into an array, splitting off each number and then concatenating those into pairs, and started getting lost around that point.

What's the best way to do this? Do I have to treat the number as a string to get the pairs, or is there a better way?

Upvotes: 1

Views: 510

Answers (1)

cnicutar
cnicutar

Reputation: 182649

What's the best way to do this? Do I have to treat the number as a string to get the pairs, or is there a better way?

You could do

while (number) {
    x = number % 100; /* Get the last two digits. */
    number /= 100; /* Get rid of them. */
}

It also depends on what you plan to do if you have an odd number of digits.

Upvotes: 3

Related Questions