Java Program to Count Digits of Number Using While Loop

By | July 2, 2019

Task: Write a Java Program to Count Digits of Number

Java Program to count digits of a number using while loop

Java Program to count digits of a number using while loop

The source of Java Program to Count digits of a number input by the user at run time is:

/*
 * Write a Java program to input a number
   and count its digit
 */
package countdigits;
/**
 * @author www.EasyCodeBook.com
 */
import java.util.Scanner;
public class CountDigits {

    public static void main(String[] args) {
        int count = 0, num, n ;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number to count its digits:");
        n = input.nextInt();
        num = n;
        while(num != 0)
        {
        num = num/10;
        count++;
        }
        System.out.println("Number of digits: " + count);
    }
}

Sample run and output of the Java Program to count digits in a number provided by the user during program execution is:

Enter a number to count its digits:123456
Number of digits: 6

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *