Sum of last digits of two given numbers
Rohit wants to add the last digits of two given numbers
Le if the given numbers are 267 and 154, the output should
Below is the explanation
Last digit of the 267 is 7
Last digit of the 154 is 4
Sum of 7 and 4 = 11
Write a program to help Rohit achieve this
The prototype of the method should be.
nublic static void addLastDigits(int inputting inputs
dinput2 denote the two numbers whose using java
Answers
Answer:
Previously we have written a Java program to find the sum of digits of the given number. Now in this post, we will write a Java program to find the sum of the first and last digit of a number.
Example:-
Number = 12345
The first digit = 1, last digit = 5
Sum of first and last digits = 1 + 5 = 6
Procedure to find the sum of first and last digit of a number in java,
Take a number
Declare sum variable and initialize it with 0
Find the last digit. To find the last digit we can use % operator. The expression number%10 gives the last digit of the number.
Find the first digit of the number. For this
Find the total number of digits in the given number.
Divide the number by 10^(total_number_of_digits-1), it will give the first digit of the number.
Add first and the last digit to the sum variable.
Answer:
import java.util.*;
public class Main{
public static void main(String[] args) {
int num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
num1 = sc.nextInt();
System.out.println("Enter second number: ");
num2 = sc.nextInt();
addLastDigit(num1,num2);
}
public static void addLastDigit(int input1, int input2){
int rem1 = input1 % 10;
int rem2 = input2 % 10;
int sum = rem1 + rem2;
System.out.println("Sum of "+rem1+" and "+rem2+ " is = "+sum);
}
}
Explanation:
In the above program, first we have taken two user input's i.e. the two numbers whose sum of last digits we want. Then we have defined a function addLastDigit() that takes two numbers and prints the sum of last digits of the two numbers. In the function, we have used modulo operator "%" to derive the last digit from the number and stored it in a variable. Lastly we have added both the last digits and displayed the result.
#SPJ2