Program to counts digits in a number

In this article we are going to count digits in a given number

Example:- if number is 23455, then the output will be 5. because the total number of digits is 5 in a given number.

Steps:-

  • First take input from the user by using a scanner.
  • declare a variable to count the digits.
  • run a while loop with a termination condition number greater than 0
  • now divide the number by 10 and increase the count by 1
  • and print the count.

Java Code to count digits in a number

package gangforcode;

import java.util.Scanner;

public class CountDigits {

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

}

Output:-

Java code to count digits in a given number

You can use the same logic to count digits in a given number by using other programing languages like c,c++, python etc.

Thanks

Leave a Comment