Monday, December 9, 2013

Finding odd or even number in VB.Net - different ways

Normally when most of the developers learn programming, they might have done the odd or even program. The basic idea is to divide by 2 and if the reminder is 0 the number is even else odd. Simple program is given below.

        If (inputNumber Mod 2) = 1 Then
            Console.WriteLine("Odd")
        Else
            Console.WriteLine("Even")
        End If

This is the normal behaviour of people who follows "do things after learning" principle. But what will happen if the person is following "learn by doing" principle. We can see a program like below

Dim total As String = Convert.ToString(inputNumber / 2, Globalization.CultureInfo.InvariantCulture)
        If total.Contains("."Then
            Console.WriteLine("Odd")
        Else
            Console.WriteLine("Even")
        End If

Interesting. Isn't it? It works. But if we look at the performance,it is not good. This may not cause a big issue in today's machines whcih have 4 cores & 8GB ram but in terms of machine cycles its a considerable factor. Surprisingly this code came from a team who consist of 2 persons who are well reputed in their organization. They started their programming in career using .Net technology (as far as I know). This again enforces my view point about programmers.

As a serious programmer one should first learn how the hardware and software work together. 

Without that knowledge also they can create and deliver good looking web sites & desktop apps in managed technologies such as .Net or Java and flourish their career. But at a later point they will struck.

1 comment:

saiju mathew stephen said...

Which is better?

Do you have data point for performance?