Sum of First and Last Digit of a Number in Java Language

Sum of First and Last Digit of a Number in Java Language – 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

<img width=

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.

Program to find Sum of First and Last Digit of a Number in Java

import java.util.Scanner;

public class SumOfFirstAndLastDigitProgram {

  // method to find sum of first and last digit
  private static int FirstLastDigitSum(int number) {

     // declare variables
     int lastDigit, firstDigit, divisor;;
     int totalDigits = 0;
     int sum = 0;

     // find last digit
     lastDigit = number%10;

     // find total number of digits
     totalDigits = findDigits(number);

     // calculate divisor value
     divisor = (int)Math.pow(10, totalDigits-1);

     // find first digit
     firstDigit = number / divisor;

     // add values
     sum = firstDigit + lastDigit;

     return sum;
  }

  // method to find total number of digits
  private static int findDigits(int number) {
     int count = 0;
     while(number!=0) {
        count++;
        number = number/10;
     }
     return count;
  }

  public static void main(String[] args) {

     // declare variables
     int number = 0;
     int sum = 0;

     // create Scanner class object 
     // for reading the values
     Scanner scan =  new Scanner(System.in);

     // read input
     System.out.print("Enter an integer number:: ");
     number = scan.nextInt();

     // find sum of digits of number
     sum = FirstLastDigitSum(number);

     // display result
     System.out.println("The sum of first & last"
            +" digit of the number "+number
            +" = "+ sum);

     // close Scanner class object
     scan.close();
  }
}


OUTPUT



Enter an integer number:: 213457
The sum of first & last digit of the number 213457 = 9

Types of Sorting Algorithms:

Additional Reading

READ MORE

If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.

Thank you 😊 Keep Learning !

Leave a Reply