VB.Net program to find the prime numbers from the array of integers

Here, we are going to learn how to find the prime numbers from the array of integers in VB.Net?
Submitted by Nidhi, on December 07, 2020 [Last updated : March 06, 2023]

Prime numbers in an array

Here, we will create an array of integers and then find the prime numbers from the array after that print them on the console screen.

Program/Source Code:

The source code to find the prime numbers from the array of integers is given below. The given program is compiled and executed successfully.

VB.Net code to print primer numbers in an array

'VB.Net program to find the prime numbers 
'from the array of integers.

Module Module1

    Sub Main()
        Dim arr As Integer() = New Integer(5) {}
        Dim flag As Integer = 0
        Dim i, j As Integer = 0

        Console.WriteLine("Enter array elements: ")
        For i = 0 To 4 Step 1
            Console.Write("Element[{0}]: ", i)
            arr(i) = Integer.Parse(Console.ReadLine())
        Next

        Console.WriteLine("Prime Numbers are: ")
        For i = 0 To 4 Step 1

            flag = 0
            For j = 2 To (arr(i) / 2) Step 1
                If arr(i) Mod j = 0 Then
                    flag = 1
                End If
            Next
            If flag = 0 Then
                Console.Write("{0} ", arr(i))
            End If
        Next
        Console.WriteLine()
    End Sub
    
End Module

Output

Enter array elements:
Element[0]: 2
Element[1]: 3
Element[2]: 4
Element[3]: 5
Element[4]: 6
Prime Numbers are:
2 3 5
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains a function Main().

In the Main() method, we created an array arr and an integer variable flag, which is initialized with 0.

Console.WriteLine("Enter array elements: ")
For i = 0 To 4 Step 1
    Console.Write("Element[{0}]: ", i)
    arr(i) = Integer.Parse(Console.ReadLine())
Next

In the above code, we read the elements of arr from the user.

Console.WriteLine("Prime Numbers are: ")
For i = 0 To 4 Step 1

    flag = 0
    For j = 2 To (arr(i) / 2) Step 1
        If arr(i) Mod j = 0 Then
            flag = 1
        End If
    Next
    If flag = 0 Then
        Console.Write("{0} ", arr(i))
    End If
Next
Console.WriteLine()

In the above code, we found the prime numbers and then print them on the console screen.

VB.Net Array Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.