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
Example C# Exercise
Show C# Code
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
}
}
Output
Case 1:
Enter a number: -345
(Warning: it is a negative number)
3 digits
Case 2:
Enter a number: 567
3 digits
Case 3:
Enter a number: -10000
(Warning: it is a negative number)
5 digits
Case 4:
Enter a number: 0
1 digit
More C# Programming Exercises of Flow Control
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
This C# exercise aims to develop a program that asks the user for a symbol and a width, and then displays a hollow square of that width using the provid...
This C# exercise aims to develop a program that asks the user for two integer numbers and shows their multiplication, but without using the "*" operator. Inste...
This C# exercise aims to develop a program that calculates (and displays) the absolute value of a number x. The absolute value of a number is its distan...
This C# exercise aims to develop a program that prompts the user for a symbol, a width, and a height, then displays a hollow rectangle of the spe...
This C# exercise aims to develop a program that allows the user to input several numbers and calculate basic statistical operations such as sum, average, mi...
This C# exercise aims to develop a program that, given a numerical grade, displays the corresponding text grade according to the following equivalence: 9 and ...