Digits in a number Learn programming Visual Basic (VB.net)


Flow Control


Digits in a number


Create a Visual Basic (VB.net) 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


Imports System
Public Class exercise38
    Public Shared Sub Main()
        Dim number As Integer
        Dim digit As Integer = 0
        Console.Write("Number? ")
        number = Convert.ToInt32(Console.ReadLine())

        If number < 0 Then
            Console.WriteLine("(Warning: it is a negative number)")
            number = -number
        End If

        While number > 0
            number = number / 10
            digit += 1
        End While

        If digit = 0 Then digit = 1
        Console.WriteLine("{0} digits", digit)
    End Sub
End Class

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.