In this program, we first input the number (Say num = 12345). Next the control reaches the while loop where it checks the condition (num>0) which is true as (12345>0) so the body of the loop is executed.
On First pass, x=5 Sum=0+5=5 num = 1234
On Second pass, x=4 Sum=5+4= 9 num = 123
On Third pass, x=3 Sum=9+3=12 num = 12
On Fourth pass, x=2 Sum=12+2=14 num = 1
On Fifth pass, x=1 Sum=14+1=15 num = 0
Finally, when the condition becomes false, the control reaches out of the loop and finally displays the sum of digits of a number. In this program, the number of times the loop will be executed is unknown in advance.
//program to Find Sum of Digits of a Number import java.util.Scanner; //program uses Scanner class public class SumDigits { public static void main(String[] args) { long num,x,sum=0; Scanner input=new Scanner(System.in); System.out.println("Enter Number :"); num=input.nextInt(); while(num>0) { x = num%10; sum += x; num /=10; } System.out.println("Sum of Digits of Number is :" +sum); } }