Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 7. Arrays > Summing the Elements of an Array

7.5. Summing the Elements of an Array

Often, the elements of an array represent a series of related values that are used in a calculation. For example, if the elements of an array represent students’ exam grades, the instructor might wish to total the elements of the array, then calculate the class average for the exam. Figure 7.3 sums the values contained in a 10-element integer array named values and displays the result in sumLabel.

Fig. 7.3. Computing the sum of the elements in an array.
 1   ' Fig. 7.3: SumArray.vb
 2   ' Computing the sum of the elements in an array.
 3   Public Class SumArray
 4      ' use a loop to sum the elements in an array
 5      Private Sub SumArray_Load(ByVal sender As System.Object,
 6         ByVal e As System.EventArgs) Handles MyBase.Load
 7
 8         Dim values() As Integer = {85, 77, 91, 44, 65, 72, 99, 84, 95, 100}
 9         Dim total As Integer = 0
10
11         ' sum the array element values      
12         For i = 0 To values.GetUpperBound(0)
13            total += values(i)               
14         Next                                
15
16         sumLabel.Text = Convert.ToString(total)
17      End Sub ' SumArray_Load
18   End Class ' SumArray

					  



  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial