first digit of a number

In this article, we are going to write code for finding the first digit of a number.

Example:-

if number = 7122344 then output will be 7.

Steps:-

  • Take a number input from user
  • run a loop while number>=10
  • Inside loop update number with number/10;
  • after the termination of loop number is the answer i.e., last digit of given number.

Java code to find last digit of a number:-

package gangforcode;
import java.util.*;

public class FirstDignum {

	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		System.out.println("Enter the number");
		int n = sc.nextInt();
		System.out.println(printFirst(n));
				
	}
	public static int printFirst(int n) {
		while(n>=10) {
			n=n/10;
		}
		return n;
		
		}
}

Output:-

Java code to find first digit of given number

You can use the same logic to find the first digit of a number using other programming languages like C, C++, Python, etc.

Leave a Comment