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.
Answers
The program to obtain the sum of the first and the last digit of a four digit number has been attached above (also its output). Kindly check it!
Program in Java :-
import java.util.Scanner;
public class FourDigit {
public static void main(String [] args) {
int num, firstDigit, lastDigit, sum;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a four digit number : ");
num = sc.nextInt();
if (num <= 9999) {
firstDigit = num / 1000;
lastDigit = num % 10;
sum = firstDigit + lastDigit;
System.out.println("Sum of first " + " and last " + " digits = " + sum);
}
else {
System.out.println("Invalid");
}
}
sc.close();
}