 Array Forloop Why it’s print out 1882? Please Help | SoloLearn: Learn to code for FREE!

+1

# Array Forloop Why it’s print out 1882? Please Help

public class Program { public static void main(String[] args) { int p=1000; int X=2881; int[]store=new int; for(int i=0;i<4;i++) { store[i]=X/p; X=X-(X/p)*p; p/=10; } for(int i=0; i<4;i++) { System.out.println(store[3-i]); } } }

7 Answers

New Answer

+2

Joseph Jostar In the expression 2881 - (2881/1000)*1000 parantheses has highest precedence so (2881/1000) will be evaluated first so 2881/1000 = 2 (fraction is discarded since it is integer division) which is then multiplied by 1000 (p value) due to higher precedence of '*' opetator so yo get X = 2881 - (2*1000) = 881 in the next statement you divide p by 10 so p = 1000/10 = 100 for next iteration X = 881, p = 100 substitute the values in expression and you get 881 - (881/100)*100 - it is calculated as above for next iteration X = 81, p = 10 so X = 81 - (81/10)*10 = 1 for final iteration p = 1 X = 1 X = 1 - (1/1) * 1 = 0

+2

Joseph Jostar You are printing the values in reverse, hence you are getting the reverse output your statement store[3-i] will access the array from back end what is your expected output? if you want to print 2881 then simply print store[i] to get the expected result

+2

~ swim ~ thank you for to share your professional knowledge and your help . X1=2881-(2881/1000)x1000 2881-2000 881 X2= 881-(881/100)x100 881-800 81 X3= 81-(81/10)x10 81-80 1 X4 = 1-(1/10)x10 1-0 1 so X= 881, 81, 1, and 1. There is no 2 and even it’s print reverse it’s not should be 1 1 81 881

+2

Joseph Jostar I didn't listed the full iterations The first digit goes in store[i] due to the statement store[i] = X/p; the above calculations are after that X = 2881, p = 1000 store = X/p = 2881/1000 = 2 After this your X1 calculation comes, which is X store = X/p= 881/100 = 8 then X2 store[2[ = X/p = 81/10 = 8; then X3 store = X/p = 1/1 = 1 then X4 = 1 - (1/1)*1 = 0 (sorry my mistake it's not 1 - (1/10)*10) i have updated my original comment after this point i becomes 4 and loop exits

+2

~ swim ~ thank you Sir now it’s make a lot of sencen for me 👍

+1

~ swim ~ i am confused with X=X-(X/p)*p X=2881 so it will be 2881-(2881/1000)*1000 so X= 0 ? i know p=1000 and it will each time ivide 10 for 4 times it will be 1000,100,10,1

+1

Joseph Jostar You are Welcome :) Glad to help you :)