Count Digits

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 28:- Count Digits

To count the number of digits in a given integer in Java, you can use a simple loop and divide the number by 10 iteratively until the quotient becomes zero. The count of divisions will give you the number of digits. Here's a Java program to count the digits in a given integer:

javaCopy code

import java.util.Scanner; public class CountDigits {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.print("Enter an integer: ");        int number = scanner.nextInt();        // Calculate the number of digits        int count = 0;        int tempNumber = Math.abs(number); // Use Math.abs() to handle negative numbers        while (tempNumber != 0) {            tempNumber /= 10;            count++;        }        System.out.println("Number of digits: " + count);        scanner.close();    } }

Example output:

mathematicaCopy code

Enter an integer: 123456 Number of digits: 6

In the program above, we take the user input for the integer and store it in the variable number. We then initialize a variable count to 0 to keep track of the number of digits. To handle negative numbers, we use Math.abs() to get the absolute value of the input number (tempNumber).

The while loop continues to divide tempNumber by 10 until tempNumber becomes 0. During each iteration, the number of digits is incremented by 1. Finally, the program prints the count of digits.

Keep in mind that the approach mentioned above works for non-negative integers. If you need to handle negative integers differently, you can adjust the logic accordingly.

6. Loops

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support