Array (OCPJP forum at Coderanch) (original) (raw)
Hi Alkesh,
I tell you a simple(easy) method to solve this type of situations. Just follow these rules . You will get the answer correct.
1. wherever you find the var just substitute the value and when you find ++/-- operator irrespective of post/pre increment/decrement (++/--) blindly increment/decrement the latest value of that var.. You have to start from left to right. So let's start
int i=5;
array[i++]=++i+i++;
array[5(6)] = (7)7 + 7(8);
(i) for i substitute the latest value of i
(ii) for ++ symbol, increment the latest value
(iii) for -- symbol, decrement the latest value
(iv) Finally do the calculation for all non-bracketed values
(v) Be careful when the assigned var is the same as the var
which undergone all these ++/-- operations in the statement.
In this case the assigned var takes its latest value
int i = 10;
ex. i = i++ + --i;
i = 10(11) + (10)10;
So i = 10 after exe of above stmt *** Notice there is an error here, it should be 20. It is corrected below ***
(vi) In order to do the arithmetic, justcut-down all the bracket values
array[5] = 7 + 7; //Note here i's latest value is 8 array[5] = 14;
(vi) Since all the elements of an int[] has default value 0,array[6] is 0.
System.out.println(array[5]+" "+array[6]+" "+i);
So it prints 14 0 8
Another example
int i=10;
int j = i++ + i + --i + ++i + i;
j = 10(11) + 11 + (10)10 + (11)11 + 11;
j = 10 + 11 + 10 + 11 + 11; // i's latest value = 11 here
j = 53;
Final answer i=11 and j=53
Easy isn't
regds
maha anna
[This message has been edited by maha anna (edited May 01, 2000).]
(Pointed out error, and the fact that it is corrected below - Barry Gaunt)
(removed HTML markup)
[ May 19, 2004: Message edited by: Barry Gaunt ]
[ May 19, 2004: Message edited by: Barry Gaunt ]