Coding Practice

Write a Java program to Find sum of first and last digit of a number

Find sum of first and last digit of a number
Sample Output
Find sum of first and last digit of a number.

Enter a number: 13334
First Digit: 1, Last Digit: 4
Sum: 5
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int n, number, firstDigit, lastDigit, sum;

        Scanner input = new Scanner(System.in);

        System.out.println("Find sum of first and last digit of a number.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();
        
        lastDigit = number % 10;
        firstDigit = number;
        
        while(firstDigit >= 10) {
            
            firstDigit = firstDigit / 10;
        }
        sum = firstDigit + lastDigit;
        
        System.out.println("First Digit: " + firstDigit + ", Last Digit: " + lastDigit);
        System.out.println("Sum: " + sum);
    }
}
Sample Output
Find sum of first and last digit of a number.

Enter a number: 9876
First Digit: 9, Last Digit: 6
Sum: 15

No comments:

Post a Comment

Change Theme
X