This java
program counts number of digits in an integer. First, user has to enter
any positive integer. If user enter negative integer, then converts it into
positive integer and if user enters 0, then convert it into 1.
Steps to count number of digits in integer:
1. Check if number is greater than 0.
2. Then, divide number by 10.
3. Increments the count variable by 1.
4. Again, go to step 1, if condition in step 1 is true, then
executes further steps, otherwise exit the loop.
Java Program to Count Number of Digits in Integer
import java.util.Scanner;class CountDigits { public static void main(String[] args) { int num, count = 0, temp; Scanner scan = new Scanner(System.in); System.out.print("Enter a Positive Integer : "); num = scan.nextInt(); temp = num; //Check if entered number is less than zero if(num<0) { num=num * -1; } //Check if number is equals to zero else if(num==0) { num=1; } for(; num>0; num = num/10, count++) { } System.out.println("Number of Digits in "+temp+" is "+count); } }
Output:
Enter a Positive Integer : 6321
Number of Digits in 6321 is 4
0 comments:
Post a Comment