Exercise
Digits In A Number
Objective
Write a C# program to calculate the number of digits in a positive integer (hint: this can be done by repeatedly dividing by 10). If the user enters a negative integer, the program should display a warning message and proceed to calculate the number of digits for the equivalent positive integer.
For example:
Number = 32
2 digits
Number = -4000
(Warning: it is a negative number) 4 digits
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
// Prompt the user to enter a number
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine()); // Reading the number entered by the user
// Check if the number is negative
if (number < 0) // If the number is negative
{
Console.WriteLine("(Warning: it is a negative number)"); // Display the warning message
number = Math.Abs(number); // Convert the number to positive using the Math.Abs() method
}
// Variable to count the digits
int digits = 0;
// Calculate the number of digits by repeatedly dividing the number by 10
while (number > 0) // Loop continues as long as the number is greater than 0
{
number /= 10; // Divide the number by 10
digits++; // Increment the digit count
}
// Display the number of digits
Console.WriteLine(digits + " digits"); // Output the total number of digits
}
}