Written by Sai Sandeep Thota on July 15, 2013 in Java > Programming

Java Program to Count the Number of Digits

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This is a simple Java program in which we take input from the user and iterate it using a while loop until it is zero. In the while loop we just divide the given number with 10 and assign it to the same input variable and increment i. The variable i is used to count the number of times while loop is iterated.

For example:
User input: 456.
That means the while loop is iterated 3 times.

import java.util.Scanner;

class digitCount {
	public static void main(String args[])
	{	
		int n, i=0;
		System.out.print("Enter a Number:");
		Scanner get = new Scanner(System.in);
		n = get.nextInt();
		while(n>0)
		{
			n=n/10;
			i++;
		}
		System.out.println();
		System.out.println("Number of Digits present : "+i);
	}
}

Output:

Java Program to Count the Number of Digits

{ 2 comments… read them below or add one }

ARIKTA SINHA May 20, 2015 at 2:16 pm

This program can also be done simply by using while loop……….

public class digit_count
{
public static void main(int s)
{
int a=0;
while(s>0)
{
s=s/10;
a=a+1;
}
System.out.println();
System.out.println(“Num of digits present here : “+a);
}
}

Reply

Biyas Mitra February 14, 2017 at 9:42 pm

This program can b done like this:-
import java.io.*;
class digit_count
{
public static void main (String args[]) throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System. out. println (“Enter a no. “);
int n =Integer.parseInt (br. readLine());
int r=0;
while ( n!=0)
{
n= n/10;
r++;
}
Systrm.out.println ( ” No. Of digits.” + r);
}
}

Reply

Leave a Comment

Previous post:

Next post: