JAstuccio
JAstuccio

Reputation: 1580

Why doesn't my code work when I use a while loop?

Tonight I was working on problem 1 from http://projecteuler.net/problem=1. It is not working using the while loop. I did get it to work using two short cut if statements. After correctly solving it I see on the forum there are better solutions using math, but I am new and need to learn what went wrong with my while loop.

Here is the question: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Correct answer = 233168

    public class Project1_Multiples_of_3_and_5 {
//Main method
public static void main (String args[])
{   
    int iResult = 0;

    for (int i = 1; i <= 1000 / 3; i++)  // for all values of i less than 333 (1000 / 3)
    {
        iResult += i * 3;  // add i*3 to iResults
        //the short cut if below works but I want to use a while loop
                //iResult +=  (i % 3 !=0 && i < 1000 / 5) ? i * 5 : 0;  // add i*5 to iResults excluding the multiples 3 added in the previous step while i < 200 ( 1000 / 5 )

        while ( (i < 1000 / 5) && (i % 3 != 0) )
        {
            iResult += i * 5;
/************************************************************************************
SOLVED!!! ... sort of
adding a break makes the code work but defeats the purpose of using a loop.  I guess     I    should just stick with my 2 if statements
************************************************************************************/

                        break;
        }//end while
    }// end for

    System.out.println(iResult);

    }//end main method
}//end class

Upvotes: 0

Views: 132

Answers (1)

Keppil
Keppil

Reputation: 46209

Your while loop never terminates, since you never change the variable (i) in the end condition:

while ( (i < 1000 / 5) && (i % 3 != 0) )
{
    iResult += i * 5; // i is not updated here
}//end while

Also, the second condition will cause the loop to exit as soon as a multiple of 3 is encountered, which is probably not what you want.
One idea could be to change this to a for loop like the one you have for the multiples of 3 (and move it out of the first for loop).

Upvotes: 6

Related Questions