How to calculate the sum of first N natural numbers in VB.NET

2 Answers

0 votes
Module Module1

    ' 1 + 2 + 3 + 4 + ... + N

    Sub Main()

        Dim n As Integer = 10, sum As Integer = 0

        While (n > 0)
            sum += n
            n -= 1
        End While

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

    End Sub

End Module

' run:
' 
' The sum is: 55


 



answered May 26, 2017 by avibootz
edited May 27, 2017 by avibootz
0 votes
Module Module1

    ' 1 + 2 + 3 + 4 + ... + N

    Sub Main()

        Dim n As Integer = 10, sum As Integer = 0

        sum = n / 2 * (n + 1)

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

    End Sub

End Module

' run:
' 
' The sum is: 55


 



answered May 26, 2017 by avibootz
edited May 27, 2017 by avibootz

Related questions

1 answer 103 views
2 answers 241 views
2 answers 233 views
2 answers 203 views
2 answers 219 views
2 answers 203 views
...