JAVA PROGRAM TO PRINT THE SUM OF DIGITS
In JAVA, the sum of digits can be calculated by using the below program.
//SUM OF DIGITS JAVA PROGRAM
import java.util.Scanner;
public class Main
{
public static void main (String[] args)
{
int num,sum =0, temp = 0;
//temp and sum are initialized with 0
Scanner snum = new Scanner(System.in);
//Scanner class used by creating an object named snum to take input
num = snum.nextInt();
// nextInt() is used to read the input from the user
System.out.println("your input is " + num);
while(num>0)
{
temp = num%10;
sum += temp;
num = num /10;
}
System.out.println("The sum of digits is " + sum);
}
}
//end of the program
OUTPUT:
456
your input is 456
The sum of digits is 15
This is embedd link for percentages chapter in apttude
<iframe width="926" height="521" src="https://www.youtube.com/embed/BXXdi2rZ_Ko" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
LOGIC EXPLANATION:
let's take 456 as input. the input will be stored inside the num variable. The while loop checks whether the input is greater than 0 or not. If the number is not greater than 0, the loop will not be executed and the output will be "sum of digits is 0". here we take 456 as input. so the compiler enters into the while loop.
1. temp = num%10; this statement represents that the remainder of the num(456) 6 is stored into temp variable.
2. sum+= temp; this statement is equals to sum = sum + temp;
we have initialized the sum value as 0. now the sum value is updated as 6( since sum= sum(0) + temp(6).
3. num = num/10; this statemet is used output will be (num = 456/10) = (num = 45).
after this statement, the while loop condition will be checked again to find whether the num value is greather than 0 or not. Since 45 is greather than 0, the loop will be executed and the varialbe values will be as follows:
num = 4; sum = 11(since 6+5=11);
Again the while loop will be executed and the variable values will be as follows:
num =0 ( since in last statement of while the 4 is divided by 10 and the result will be 0).
sum = 15( since 6+5+4 = 15).
Again the condition for the while loop will be checked. But the condition will be false. so the statement next to the while loop will be executed by the executed.
i.e., The sum of digits =15
Luckiest gal
ReplyDelete