Absolute value Learn programming Visual Basic (VB.net)


Flow Control


Absolute value 21


Write a Visual Basic (VB.net) program to calculate (and display) the absolute value of a number x: if the number is positive, its absolute value is exactly the number x; if it is negative, its absolute value is -x.

Do it in two different ways in the same program: using "if" and using the "conditional operator" (?)


Imports System
Public Class Exercise41
    Public Shared Sub Main()
        Dim n, abs As Integer
        Console.Write("Enter a number: ")
        n = Convert.ToInt32(Console.ReadLine())

        If n < 0 Then
            abs = -n
            abs = n
        End If

        Console.WriteLine("Absolute valor is {0}", abs)
        abs = If(n < 0, -n, n)
        Console.WriteLine("And also {0}", abs)
    End Sub
End Class