VB.Net program to calculate the sum of all elements of an integer array

Here, we are going to learn how to calculate the sum of all elements of an integer array in VB.Net?
Submitted by Nidhi, on December 07, 2020 [Last updated : March 06, 2023]

Find the sum of all elements of an integer array in VB.Net

Here, we will create an array of integers and then read elements from the user after that calculate the sum of all elements and print the sum on the console screen.

Program/Source Code:

The source code to calculate the sum of all elements of the integer array is given below. The given program is compiled and executed successfully.

VB.Net code to find the sum of all elements of an integer array

'VB.Net program to calculate the sum of 
'all elements of an integer array.

Module Module1

    Sub Main()
        Dim arr As Integer() = New Integer(5) {}
        Dim sum As Integer = 0

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

        Console.WriteLine("Sum of array elements is: {0}", sum)
    End Sub
    
End Module

Output:

Enter array elements:
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 56
Element[4]: 34
Sum of array elements is: 150
Press any key to continue . . .

Explanation:

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

Dim arr As Integer() = New Integer(5) {}
Dim sum As Integer = 0

In the Main() we created an array arr of five elements and an integer variable sum, which is initialized with 0.

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

Console.WriteLine("Sum of array elements is: {0}", sum)

In the above code, we read the elements of the array from the user and calculate the sum of array elements and print the total on the console screen.

VB.Net Array Programs »





Comments and Discussions!

Load comments ↻





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