next up previous
Next: 17. PictureBoxes Up: VisualBasic Previous: 15. Inputting from a


16. Calculating the Sum of some numbers

Often we will want to calculate the following sum:

\begin{displaymath}
Sum = \sum_{i=1}^{N} X_i \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\...
...\;\;\;\;
\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; (1)
\end{displaymath}

for example to calculate the average of some numbers.

Lets assume that the X's are stored in a data file. The following code calculates the above sum:

Dim Sum, X As Double

Open "EXAMPLE2.DAT" For Input As #4

Sum = 0  ' This just makes sure that Sum is initialised to zero

While Not EOF(4)
Input #4, X
Sum = Sum + X
Wend

Print "The Sum of all the X = ", Sum

Close #4

In the above, we firstly declare the variables Sum and X as real numbers (specifically Double) - see Sec. [*]. We then open the data file EXAMPLE2.DAT which has been prepared before to contain the numbers X which we want to sum. (EXAMPLE2.DAT should have all these X values one per line.) The line Sum = 0 just initialises Sum just in case it has been used previously!

The While loop (see Sec. [*]) is designed to read in all the number in the file EXAMPLE2.DAT until the end-of-file is reached. Then comes the important line:

Sum = Sum + X

If this is viewed mathematically, it looks a bit odd (it would imply that X=0 !!). But what this really means is to calculate the R.H.S. (i.e. add Sum to X), and assign it to the variable on the L.H.S., (i.e. Sum). In the above case, the old value of Sum will be overwritten.

Each time through the While loop, the variable Sum will accumulate another term, and, at the end of the loop, the Sum in Eq.(1) will be calculated.

The above example can be generalised to calculating the following sum:

\begin{displaymath}
Sum = \sum_{i=1}^{N} X_i^2
\end{displaymath}

by simply replacing the Sum = Sum + X with Sum = Sum + X^2.

If you need to calculate the sum of some numbers, then the code above, or some generalisation of it, is the way to go.


next up previous
Next: 17. PictureBoxes Up: VisualBasic Previous: 15. Inputting from a
Chris Allton 2006-10-27