# A little problem about a Nine-times Table

• 05-03-2012, 05:17 PM
blackdiz
A little problem about a Nine-times Table
I try to make a nine-times table program example on a book and here's the code.
Code:

```public class NineTable2 {         public static void main(String[] args) {                 for (int i = 2, j = 1; j < 10; i = (i == 9) ? ((++j / j) + 1) : (i + 1)) {                         System.out.printf("%d*%d=%2d%c", i, j, i * j, (i == 9 ? '\n' : ' '));                 }         } }```
it works ok, but If I change the code:
Code:

`i = (i == 9) ? ((++j / j) + 1) : (i + 1)`
to
Code:

`i = (i == 9) ? ((j++ / j) + 1) : (i + 1)`
When i == 9 , it always makes i = 1.
But does not j++ is as same as ++j?if ++j can make i = 2,so should j++,but it doesn't happen and i always equals 1.Can somebody explain it why:s:
Sorry for my poor English, hope you can understand my question.
Best Regard
• 05-03-2012, 05:22 PM
Norm
Re: A little problem about a Nine-times Table
Quote:

j++ is as same as ++j
No
The position of the ++ determines when the value of the variable is returned.
If it is before the variable the value returned is after the ++ is done, if after, the value is before the ++ is done.
• 05-03-2012, 05:49 PM
blackdiz
Re: A little problem about a Nine-times Table
So if j = 1,then (++j/j) + 1 means j will add 2 first , then return value, so (++j/j) + 1 will run as ((1+1)/2) + 1 and equals 2,right?
And ((j++)/j) +1 means ((1+1)/1)+ 1 and equals 3,right?
But when I run the program with ((j++)/j) +1, I guess it runs (0/1)+1=1,so i is always 1, I don't know why ((j++/j)+1 = 1
• 05-04-2012, 04:29 AM
brynpttrsn
Re: A little problem about a Nine-times Table
Quote:

Originally Posted by blackdiz
So if j = 1,then (++j/j) + 1 means j will add 2 first , then return value, so (++j/j) + 1 will run as ((1+1)/2) + 1 and equals 2,right?
And ((j++)/j) +1 means ((1+1)/1)+ 1 and equals 3,right?
But when I run the program with ((j++)/j) +1, I guess it runs (0/1)+1=1,so i is always 1, I don't know why ((j++/j)+1 = 1

Almost but not quite.

++j will add 1 to j before the result of j is returned.
j++ adds 1 to j after the result of j is returned
Therefore:
if j = 1
++j will return 2.
j++ will return 1 but will be 2 after.

Demonstration:

(++j/j)
if j = 1 this will translate to:
(2/2)
No matter what j is, this will always evaluate to 1

(j++/j)
if j = 1 this will translate to:
(1/2)
now this is the important part
at first glance this appears to evaluate to .5
BUT! The data type you are using is int therefore it will evaluate to 0!

Reason:
int cannot hold numbers with decimal places therefore truncates the decimals leaving the hole number(in this case 0).

Conclusion:
(++j/j) + 1
(2/2)+1
1+1
2

(j++/j) + 1
(1/2) + 1
0 + 1
1
• 05-04-2012, 07:09 AM
blackdiz
Re: A little problem about a Nine-times Table