Java Program to find sum of first and last digit of a number


In this program, You will learn how to find sum of first and last digit of a number in Java.


2341 => 2 + 1 = 3


Example: How to find sum of first and last digit of a number in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int r, n, rev = 0, fd, ld, s;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a Number :");
        n = sc.nextInt();

        ld = n % 10;

        while (n > 0) {
            r = n % 10;
            rev = rev * 10 + r;
            n = n / 10;
        }

        fd = rev % 10;
        s = fd + ld;

        System.out.println("\nThe Sum of First and Last Digit is :" + s);

    }
}

Output:

Enter a Number :151
The Sum of First and Last Digit is :2