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

Lesson:

Flow Control


Exercise:

Digits in a number 47


Objetive:

Create a Visual Basic (VB.net) program to calculate how many digits has a positive integer (hint: it can be done by dividing by 10 several times). If the user enters a negative integer, the program must show a warning message, and proceed with the equivalent positive number.

For example:
Number = 32
2 digits
Number = -4000
(Warning: it is a negative number) 4 digits


Code:

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