What's the logic behind this code?

• 06-26-2013, 05:50 AM
tonie
What's the logic behind this code?
I know how to write this code but don't understand the logic how it comes to "Product = 24". Would greatly appreciate it if someone could write out the steps.

Code:

``` int product = 1;   int i = 1;   while ( i < 5 )   {         product = product * i;         i = i + 1;   }   System.out.println( “product = “ + product );```
• 06-26-2013, 05:55 AM
DarrylBurke
Re: What's the logic behind this code?
Quote:

Originally Posted by tonie
I know how to write this code but don't understand the logic

The how did you write it?

db
• 06-26-2013, 06:44 AM
tonie
Re: What's the logic behind this code?
I just know it's 1*2*3*4, but I don't know how to interpret it or explain it.
• 06-26-2013, 06:51 AM
DarrylBurke
Re: What's the logic behind this code?
• 06-26-2013, 07:14 AM
tonie
Re: What's the logic behind this code?
Didn't read the above but this is what I got in excel when I typed it out. I hope it's right.

Pro = 1 * 1 = 1-----I = 1 + 1 = 2
Pro = 1 * 2 = 2-----I = 2 + 1 = 3
Pro = 2 * 3 = 6-----I = 3 + 1 = 4
Pro = 6 * 4 = 24----I = 1 + 1 = 5 <-- stop at 5.

Am I right?
• 06-26-2013, 07:39 AM
JosAH
Re: What's the logic behind this code?
Quote:

Originally Posted by tonie
Am I right?

Yep, you're right; simply follow the algorithm step by step and you get 24 as the end result.

kind regards,

Jos
• 06-26-2013, 07:42 AM
tonie
Re: What's the logic behind this code?
Thank you for confirming my answer, Jos. Very much appreciated.
• 06-26-2013, 08:13 AM
Junky
Re: What's the logic behind this code?
Excel?

Didn't you have any paper handy?
• 06-26-2013, 08:15 AM
tonie
Re: What's the logic behind this code?
LOL... I do. I was doing it on paper, but I decided to do it on excel because I needed to copy and paste it here.