1

Array a of ints contains the digits of a number. For this example I'll insert random numbers but the code must work for any set of numbers. I have to add together the ints in the array and then store the last digit in that sum into a variable called checksum.

In this example, 3 + 5 + 7 = 15 so checksum would = 5. Here's my code so far. How would I go about calculating the checksum?

int[] a = { 3, 5, 7 }; 

int checksum = 0;
int i = 0;

while ( i < a.length )
    {
        checksum += a[i];
        i++;
    }

checksum = ???????;
daniel gratzer
  • 52,833
  • 11
  • 94
  • 134
user1713336
  • 131
  • 5
  • 14

1 Answers1

2

Simply use the modulus operator. checksum %= 10

This basically means, set checksum to the remainder of checksum/10 which happens to be the last digit.

Edit:

Just to offer another suggestion, your while loop is really better suited to be a for-each loop, just try:

for(int i : a){
    checksum += i;
}

Read it as "Forint i in a". IMHO this is slightly more understandable and you avoid some typing.

daniel gratzer
  • 52,833
  • 11
  • 94
  • 134