Write a Java program to count number of digits in a number. In this program, We take a number as an input and print the count of digit in a number.
C, C++ Program to count number of digits in a number
Java program to print factorial of a number
Java program to reverse a string
Java programs
Output :
Enter a number - 356
Number of digits in a number is - 3
Let's understand how this program works-
Iteration 1 - Our input number is 356
In first iteration, value of num variable is 356.
num = num / 10 = 35
count = 1
Iteration 2
After first iteration, value of num variable is 35.
num = num / 10 = 3
count = 2
Iteration 3
After second iteration, value of num variable is 3.
num = num / 10 = 0
count = 3
After third iteration our while loop terminate, As it not satisfy the condition (num is greater than zero). So our program will print number of digits in a number is 3.
C, C++ Program to count number of digits in a number
Java program to print factorial of a number
Java program to reverse a string
Java programs
Java Program to Count Number of Digits in a Number
import java.util.*; public class CountDigit { public static void main(String[] args) { int num, count = 0; System.out.println("Enter a number"); Scanner in = new Scanner(System.in); num = in.nextInt(); while( num > 0) { //Reduce number in each iteration num = num / 10; //count count++; } System.out.println("Number of digits in a number is "+ count); } }
Output :
Enter a number - 356
Number of digits in a number is - 3
Let's understand how this program works-
Iteration 1 - Our input number is 356
In first iteration, value of num variable is 356.
num = num / 10 = 35
count = 1
Iteration 2
After first iteration, value of num variable is 35.
num = num / 10 = 3
count = 2
Iteration 3
After second iteration, value of num variable is 3.
num = num / 10 = 0
count = 3
After third iteration our while loop terminate, As it not satisfy the condition (num is greater than zero). So our program will print number of digits in a number is 3.
No comments:
Post a Comment