Dremendo Tag Line

Input a number and count digits using a function in Java

Function - Question 1

In this question, we will see how to input a number and count how many digits are there in it in Java programming using a function. To know more about function click on the function lesson.

Q1) Write a program in Java to input a number and count how many digits are there in it using a function.

Program

import java.util.Scanner;

public class Q1
{
    public static int countdigit(int num)
    {
        int dc=0;
        while(num>0)
        {
            dc=dc+1;
            num=num/10;
        }
        return dc;
    }

    public static void main(String args[])
    {
        int n;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a number ");
        n=sc.nextInt();
        System.out.print("Total Number of Digits = "+countdigit(n));
    }
}

Output

Enter a number 42863
Total Number of Digits = 5
video-poster