In: Computer Science
write a java code, please do not use method and demo
Consider a four digit number such as 6587. Split it at two digits, as 65 and 87. Sum of 65 and 87 is 152. Sum of the digits of 152 is 8. Given the starting and ending four digit numbers and a given target number such as 10, write a program to compute and print the number of instances where the sum of digits equals the target.
Java code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args){
Scanner input=new
Scanner(System.in);
//initializing starting
value,ending value,target,first and second half values,sum of them
and the total of digits of sum
int
start,end,target,count=0,h1,h2,sum,total;
//asking for starting and ending
value
System.out.print("Enter starting
and ending value: ");
//accepting starting value
start=input.nextInt();
//accepting ending value
end=input.nextInt();
//asking for target
System.out.print("Enter target:
");
//accepting target
target=input.nextInt();
//looping from start to end
for(int
i=start;i<=end;i++){
//finding
first half value
h1=i/100;
//finding
second half value
h2=i%100;
//finding
their sum
sum=h1+h2;
//initializing it's digits total as 0
total=0;
//looping
till sum is 0
while(sum!=0){
//adding last
digit of sum to total
total+=sum%10;
//removing last
digit of sum
sum/=10;
}
//checking
if total equals to target
if(total==target)
//incrementing count
count++;
}
//printing count
System.out.println("Number of
instances="+count);
}
}
Screenshot:
Input and Output: