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.

 

Disclaimer:-

Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.

 

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?