[Solved] How to store a big number in parts in an array and then add up the digits?


Problem

You want to divide your integer to 3 different parts. Basically, you have a number 54353325421435, and you want to divide it up into:

part[0]=54353
part[1]=32
part[2]=5421435

Then add them up.

Solution

A for loop will do best. If you don’t know what a for loop is, basically it’s a means of iteration with a defined starting and ending point. For example, here is a simple iteration that prints out “hello world” 2 times:

for(int i=0; i<2; i++)
   cout << "Hello World" << endl;

You can learn more about for loops here. In your case, what you want to do is iterate through this. So basically, first you store the variable in an integer. (I’m sure you can do that.)

 const unsigned long long NUM = 54353325421435; //Make it a constant to not change it

And then you have an array of parts as you mentioned above:

int part[3]

What you can do now is, loop through the NUM. So let me show you how to do the first one:

int access_digits(const unsigned long long int n, int index)
{
    int digit_array[64] = {0};

    unsigned long long digits = 0, digit, number = n;
    while (number) {
        digit = number % 10;
        number /= 10;
        digit_array[digits] = digit;
        digits++;
    }

    return digit_array[digits - index - 1];
}

 std::string digits;
 for(int i=0; i<=4; i++)
 {
    digits.append(std::to_string(access_digits(NUM,i)));
 }
 int digit_int = std::stoi( digits );

You can see above, first that there is an access_digits function. You can use that function to access digits by index. (Credit goes toward Slayther.) Anyway, after that, you can see I am looping from 0 to 4 to get the first 5 digits for part[0]. The first 5 digits bring 54353.

Now finally you want to add them up. Well, again that’s pretty easy. Just loop through the digits, and have an accumulator add them up like so:

  int accum=0;
  for(int i=0; i<4; i++)
  {
    accum += access_digits(digit_int,i);
  }
 

Exercise

Now edit this to include part[1] and part[2] below on the exercise section.

References

Iterating through digits in integer in C

Teenage Territory chat

for loop

std::string

string::append

Glossary

For Loops:

Executes init-statement once, then executes statement and iteration_expression repeatedly until the value of condition becomes false. The test takes place before each iteration.

Syntax

formal syntax:

attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement

informal syntax:

  attr(optional) for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) ) statement

2

solved How to store a big number in parts in an array and then add up the digits?