+ 6

[SOLVED]Please Explain me this code!

this program works like this 1)Enter 2 digit eg 22 2) its add the 2 digits like =》 22 =》2+2 =4 P.S. I got this code from my teacher can someone here can explain me this code. import java.util.*; class sum_digits { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter a number"); int n=sc.nextInt(); int s=0,x; while(n!=0) { x=n%10; s+=x; n/=10; }

5th Nov 2017, 2:13 PM
Riyad Arshad
Riyad Arshad - avatar
5 Answers
+ 9
When your while loop runs first: x = 22%10 = 2 s += 2 = 2 n /= 10 = int 22/10 = 2 Now the value of x = 2, s = 2 and n = 2 When your while loop runs second: x = 2%10 = 2 s += 2 = 2+2 n /= 10 = int 2/10 = 0 Now the value of x = 2, s = 4 and n = 0 And now your while loop will stop executing because n == 0, so the code stops. Hope you will understand.
5th Nov 2017, 2:22 PM
Tim Thuma
Tim Thuma - avatar
+ 9
If the input is 27, initially n = 27, s = 0. Here s is storing the sum. The loop will run 🏃 until n is 0 Iteration 1: x = 27%10 = 7 s = 0+7 = 7 n = 27/10 = 2 Iteration 2: x = 2%10 = 2 s = 7+2 = 9 n = 2/10 = 0 Since n is 0 now, the loop will be stopped.
5th Nov 2017, 2:20 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 7
I was not able to understand the statements inside the while loop but now im Happy that i get a Good response thus now im able to understand the logic behind this complex code. Thank you all For you Kindness ... Appreciate your Efforts 😊😊
5th Nov 2017, 2:54 PM
Riyad Arshad
Riyad Arshad - avatar
+ 4
1 Scanner sc=new Scanner(System.in); 2 System.out.println("Enter a number"); 3 int n=sc.nextInt(); 4 int s=0,x; 5 while(n!=0) 6 { 7 x=n%10; 8 s+=x; 9 n/=10; 0 } Line 1 declares a scanner to process input from the console Line 2 displays a prompt to the console Line 3 reads an integer from the console Line 4 declares & zeros s and declares x Line 5 tests n for zero, if 12 was entered n will be 12 the first time, 1 the second, and 0 the third Line 7 sets x to the digit being removed by getting the ones column, it will be 2 the first time and 1 the second Line 8 adds x to s making it 2 the first time and 3 the second Line 9 gets the 10s column and beyond and replaces n with it, it will be 1 the first time and 0 the second. Line 0 goes back to line 5
5th Nov 2017, 2:36 PM
John Wells
John Wells - avatar
+ 2
which part dont you understand?
5th Nov 2017, 2:16 PM
Jeremy
Jeremy - avatar