usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Simple Code for Listing Even Numbers in Visual Basic - Fun Exercise for Young Students



What are Even Numbers? | Maths Explanation for VB.Net Kids

Hello pupils, what are even numbers?
Answer:
Even numbers are numbers that are divisible by 2.

They include:

2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, ...

Considering how simple and straight-forward even numbers are, writing a Visual Basic code for even numbers serves as a great way to introduce our Mathematics educational activities for young learners.
Well then, let's see how we can write a programming code to make our computer list a set of even numbers in the Visual Basic language, between a given range of values. Bear in mind, we use only a loop and a simple conditional statement for the Visual Basic code.

Create a new Visual Basic Console Project; call it Arithmetic.vb.
You can rename the module name -- just right-click on the name from the Solution Explorer panel -- to EvenModule if you want.
Create a new Visual Basic Class File; call it EvenNumbers.vb.

Type out the adjoining Visual Basic code for listing even numbers.


So! Visual Basic Fun Practice Exercise - List Even Numbers

As a fun practice exercise, feel free to try out your own boundary values, and see how the Visual Basic code lists the even numbers between those boundary values.







VB.Net Code for Even Numbers - Class File.

Public Class EvenNumbers

    Dim first As Integer
    Dim last As Integer
    Dim result As New List(Of Integer)

    ' Simulate a constructor
    Public Sub _init_(alpha As Integer, omega As Integer)
        first = alpha
        last = omega
    End Sub

    ' Returns an list Of the desired Set Of even numbers
    Public Function prepResult() As List(Of Integer)
        ' Loop from start to stop and rip out even numbers;

        Dim i = 0
        For i = first To last
            If i Mod 2 = 0 Then ' modulo(%) is explained later
                result.Add(i)
            End If
        Next i

        Return result
    End Function

End Class

VB.Net Code for Even Numbers - Main Module.

Module Arithmetic_EvenNumbers

    Sub Main()

        ' Use the even number Class
        Dim lower_boundary = 1
        Dim upper_boundary = 100
        Dim even_list As New EvenNumbers
        even_list._init_(lower_boundary, upper_boundary)
        Dim answer = even_list.prepResult()

        Console.WriteLine("Even numbers between " & lower_boundary & " and " & upper_boundary & " are:")
        Console.Write(String.Join(", ", answer))

    End Sub

End Module



<< PreviousNext >>