Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am using visual studio and i have selected a console application

i have a list of numbers: 3, 4, 2
and i want to add them together using any iterative method
how would i do this?

What I have tried:

VB.NET
Module Module1

    Sub Main()
        Dim numbers() As Integer = {4, 3, 2}
        Dim sum As Integer
        Dim finished As Boolean = False

        While finished = False
            Console.WriteLine(numbers)

            sum =
        End While
        Console.ReadLine()
    End Sub

End Module
Posted
Updated 19-Mar-18 10:12am
v2

In addition to solution #1 by Richard Deeming[^]...

This:
VB.NET
Dim numbers() As Integer = {4, 3, 2}

is NOT a list. It's an array of integers.

This is a List(Of Integer)[^]:
VB.NET
Dim myList As New List(OF Integer)()
myList.Add(4)
myList.Add(3)
myList.Add(2)


How to: Create a List of Items | Microsoft Docs[^]

There's at least few ways to achieve that:
1. For Each ... In ... Next[^]
This way you know now

2. For ... Next[^]
VB.NET
Dim numbers() As Integer = {4, 3, 2}
Dim sum As Integer = 0

For i As Integer = 0 To numbers.Length -1
	sum += numbers(i)
Next

Console.WriteLine("Sum: {0}", sum)


3. While ... Loop Until or Do ... While ...[^]

VB.NET
While i < numbers.Length
	sum += numbers(i)
	i +=1
End While


VB.NET
Do 
	sum += numbers(i)
	i +=1
Loop While i < numbers.Length



For further details about loops, please reaad this: Loop Structures (Visual Basic) | Microsoft Docs[^]

Another way to achieve that is to use Linq:
VB.NET
Dim sum = numbers.Sum(Function(x) x)


See:
LINQ: .NET Language Integrated Query[^]
Introduction to LINQ in Visual Basic | Microsoft Docs[^]

Good luck!
 
Share this answer
 
v3
VB.NET
Dim numbers() As Integer = {4, 3, 2}

Dim sum As Integer = 0
For Each number As Integer In numbers
    sum += number
Next

Console.WriteLine(sum)

For Each...Next Statement (Visual Basic) | Microsoft Docs[^]
 
Share this answer
 
Comments
Maciej Los 19-Mar-18 16:13pm    
Good one!
[EDIT]
Few more details in y answer ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900