Re: Program will add but cannot get it to multiply



On 2006-01-31, shannon penned:
> Hi,
> Just started Java and want to multiply odd numbers between 1 and 100.
> However, at the moment i can only get them to add. I tried replacing
> the + sign with the * multiplication sign but to no avail. Any
> suggestions?
>
>
> int sum = 0;
>
> for ( int number = 0; number <=100; number +=2 )
> sum += number;
>
>
> JOptionPane.showMessageDialog ( null, "The sum is " + sum, "Sum Odd
> Integerts from 1 to 100", JOptionPane.INFORMATION_MESSAGE );

Yup. Walk through the loop.

Your loop starts with number = 0.

Then you multiply sum by 0, resulting in sum = 0.

And then you keep multiplying 0 by stuff, all of which of course
results in 0.

--
monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
.



Relevant Pages

  • Program will add but cannot get it to multiply
    ... Just started Java and want to multiply odd numbers between 1 and 100. ... Prev by Date: ...
    (comp.lang.java.help)
  • Re: threads and GUIs
    ... idea to run things in a loop, currently instead iterations beyond the first are activated manually) would somehow waste memory. ... Java manages memory for you. ... Foo foo = new Foo; ... Java is optimized for short-lived objects, ...
    (comp.lang.java.programmer)
  • Re: StackOverflow Exception in JNI
    ... > I have a loop written in C/JNI which calls back a Java object (which ... temporary objects in your native method and then return a valid ... reference without thinking too much about these issues. ...
    (comp.lang.java.programmer)
  • Re: Challenge: Loop in Common Lisp and in Java
    ... > In the process of extending Linj (the Lisp to Java compiler) to support ... > the extended loop macro, I found some funny examples in Paul Dietz ANSI ... > challenges for the Common Lisp community. ...
    (comp.lang.lisp)
  • Re: Are there any Garbage Collector improvements?
    ... Foo foo = new Foo; ... loop so that it can be GCed by a minor collection instead of a major ... The referenced links explain it better than I probably can, but the key is that Java uses a generational garbage collector. ... Young generation collections are very fast, and object creation is blazingly fast. ...
    (comp.lang.java.programmer)