Sum Fist an Last Digits Numbers in Java


If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.


The program first prompts the user to enter a four-digit number using the System.out.println statement and then reads the input using the Scanner class.

After that, the program uses the modulus operator % and the division operator / to extract the first and last digits of the input number and add them to the sum variable. This is done by first calculating the remainder of the number when divided by 10, which gives the last digit of the number. The last digit is then added to the sum variable. Next, the number is divided by 1000 to remove the first three digits, and the remainder of this division operation is taken to get the second digit from the right, which is added to the sum variable.

Finally, the program outputs the sum of the first and last digits using the System.out.println statement. Note that this program assumes that the user inputs a valid four-digit number. If the user inputs a number with fewer or more than four digits, the program may not work as intended.

Source Code

import java.util.Scanner;
class Sum_of_First_Last_Digits
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the Four Digits Numbers :");
		int num = input.nextInt();
		System.out.println("Original Digits :"+num);	
		int rem,sum=0;
		rem=num%10;
		num=num/1000;
		sum=sum+rem;
 
		rem=num%10;
		sum=sum+rem;
		System.out.println("Sum of First Last Digits :"+sum);
	}
}

Output

Enter the Four Digits Numbers :
2534
Original Digits :2534
Sum of First Last Digits :6