Block of Code

Practical Examples for Programmers

  • Home
  • C++
  • Java
  • Visual Basic
  • Discrete Math
  • Ask a Question

Sum of Numbers

The file Numbers.txt contains a list of integers.  Write a program that displays the number of integers in the file and their sum.  See the figure below for a possible outcome.

Sum Of Numbers

The figure below shows the file contents which were used to create the above outcome.  You can create this file using Notepad.

Sum of Numbers screenshot 2

Suggested Control Names and Attributes:

Name Property Text Property Control Type Notes
 frmSumOfNumbers Numbers Form Holds Controls
 btnDisplay Display Values Button Triggers event to display output
 lstValues ListBox Displays number of integers and their sum

Write the Code:

' Project: Sum of Numbers
' Description:  This program reads a text file containing numbers and populates the data into a 
' temporary array of strings.  That array is then transferred into another array of integers so 
' that it can be manipulated.  When the user clicks "Display Values" button, the program displays
' the total number of integers in the list and the sum of those numbers.

Public Class frmSumOfNumbers
    ' Declare global variables
    Dim tempNumbers() As String = IO.File.ReadAllLines("numbers.txt")
    Dim numbersCount As Integer = tempNumbers.Count
    Dim numbers(numbersCount - 1) As Integer

    Private Sub frmSumOfNumbers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Transfers values from temp string array into array of integers for manipulation
        For i As Integer = 0 To numbers.Count - 1
            numbers(i) = CInt(tempNumbers(i))
        Next
    End Sub

    Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
        lstValues.Items.Add("Number of integers in the file: " & numbersCount)
        lstValues.Items.Add("Sum of integers in the file: " & CStr(CalculateSum()))
    End Sub

    Function CalculateSum() As Integer
        Dim sum As Integer = 0
        For i As Integer = 0 To numbers.Count - 1
            sum += numbers(i)
        Next
        Return sum
    End Function
End Class

Secondary Sidebar

This is the secondary sidebar

Copyright © 2025 · Metro Pro Theme on Genesis Framework · WordPress · Log in