Coding Practice

Write a Java program to find first and last digit of a number

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

Enter a number: 1445
First Digit: 1
Last Digit: 5
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int n, number, firstDigit, lastDigit;

        Scanner input = new Scanner(System.in);

        System.out.println("Find 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;
        }
        System.out.println("First Digit: " + firstDigit + "\nLast Digit: " + lastDigit);
    }
}
Sample Output
Find first and last digit of a number.

Enter a number: 2021
First Digit: 2
Last Digit: 1

No comments:

Post a Comment

Change Theme
X