Jessie
Jessie

Reputation: 47

Do while loops (Java)

Im trying to write a program to sum each digit of every 4 digit number. For example, I start with 1000 and once 1001 is added the thousands become 2, hundreds become 0, tens becomes 0 and units becomes 1. This should keep adding each number until it reaches 9999. This is my code, it just outputs 9999.

int num = 1000, unit = 0, ten = 0, hundred = 0, thousand = 0, newNum = 0, sumth = 0, sumh = 0, sumten = 0, sumu = 0;

while (num <= 9999)
{
    unit = num%10;
    newNum = num/10;
    ten = newNum%10;
    newNum=newNum/10;
    hundred = newNum%10;
    thousand = newNum/10;
    num++;
}
sumth = thousand + sumth;
sumh = hundred + sumh;
sumten = ten + sumten;
sumu = unit + sumu;

System.out.println(sumth + " " + sumh + " " + sumten + " " + sumu);

Upvotes: 0

Views: 108

Answers (2)

sinsuren
sinsuren

Reputation: 1754

It should be shifted inside while loop

while (num <= 9999)
    {
        unit = num%10;
        newNum = num/10;
        ten = newNum%10;
        newNum=newNum/10;
        hundred = newNum%10;
        thousand = newNum/10;

        sumth = thousand + sumth;
        sumh = hundred + sumh;
        sumten = ten + sumten;
        sumu = unit + sumu
        num++;    

    }


Output: 45000 40500 40500 40500
Working link: https://ideone.com/WrAX8D

Upvotes: 0

jamesfmackenzie
jamesfmackenzie

Reputation: 111

Tidying this up a little for readability:

int num = 1000,
    sumThousands = 0,
    sumHundreds = 0,
    sumTens = 0,
    sumUnits = 0;

    while (num <= 9999)
    {
        int units = num % 10;
        int tens = (num / 10) % 10;
        int hundreds = (num / 100) % 10;
        int thousands = (num / 1000) % 10;

        sumUnits += units;
        sumTens += tens;
        sumHundreds += hundreds;
        sumThousands += thousands;

        num++;
    }

System.out.println(sumThousands + " " + sumHundreds + " " + sumTens + " " + sumUnits);

The output you'll get is:

45000 40500 40500 40500

This is expected. For the sequence of integers 1000..9999:

  • In the thousands column, every digit 1..9 is repeated 1000 times
    • So the thousands sum is 1000(9+8+7+6+5+4+3+2+1) = 1000(9(10)/2) = 45000
  • In every other column, every digit 0..9 is repeated 900 times
    • So the sums for the other columns are 900(9+8+7+6+5+4+3+2+1) = 900(9(10)/2) = 40500

Upvotes: 1

Related Questions