Exercise
Digits in a number
Objetive
Create 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
Example Code
using System;
public class exercise38
{
public static void Main()
{
int number;
int digit = 0;
Console.Write("Number? ");
number = Convert.ToInt32(Console.ReadLine());
if (number < 0)
{
Console.WriteLine("(Warning: it is a negative number)");
number = -number;
}
while (number > 0)
{
number = number / 10;
digit++;
}
if (digit == 0)
digit = 1;
Console.WriteLine("{0} digits", digit);
}
}