In: Computer Science
Write a java code to find the following. For numbers 501 to 999, how many numbers will have the sum of the digits equal to 10.
501, sum of digits=6
502, sum of digits=7
503, sum of digits=8
504, sum of digits=9
505, sum of digits=10
506, sum of digits=11
Here i am writing the code in the java. after this // i will explain about that line
First what is the logic for this program;
logic will be we will make a function or method in java which gives us sum of digit then after getting sum of digit we will compare and if match then we will count it.
code : ( Note: make sure your java program file name and in the code name should be same )
public class Main
{
public static void main(String[] args) { //program starts now
int count=0; // declaring the variable count which will count the sum of digit is equal to 10
int temp=0; // temp variable which will store sum of digit
for(int i=501;i<=999;i++) // for loop declaration 501 to 999
{
temp = sumFunction(i); // calling sum function which is created in the below and store the sumfunction value in temp variable
if(temp==10) //now checking for equal to 10 if match then it will increment the value of count by 1
{
count++;
}
}
System.out.print(count); // after all done print the value of count then we get how many number are there in the range which sum of digit is equal to 10
}
public static int sumFunction(int x) // creating function and taking x variable
{
int sum=0; // declaring sum variable where sum will store
while(x!=0) // till x not equal to 0 the loop will run
{
sum=sum+x%10; // sum of digit algorithm,
x=x/10;
}
return sum; // when loop complete the function will return sum.
}
}
Output is 20