QBASIC – Sum of numbers from 1 to 5

Let’s understand how to calculate the sum of numbers from 1 to 5. The program below will display the total of all numbers from 1 to 5 i.e., 1 + 2 + 3 + 4 + 5.

' Program to find sum of numbers from 1 to 5
CLS
sum = 0
FOR i = 1 TO 5
  sum = sum + i
NEXT i
PRINT "Sum of numbers from 1 to 5 is ";sum
END

Explanation:

This is a little different use of the FOR looping statement. If you remember in the program to display the numbers from 1 to 5, the PRINT i statement was executed inside the loop while in this program, we are calculating the sum using sum = sum + i inside the loop.

Also, note that before the loop the variable sum is initialized to 0. This variable is known as an accumulation variable used to calculate and store the total of the sum of numbers in this case.

Another thing to notice, PRINT statement is not executed inside the loop but outside the loop. The reason behind this is we are calculating the sum inside the loop and if we use PRINT inside the loop, each time the loop runs, the PRINT statement executes which is not the requirement here.

Leave a Comment

Your email address will not be published. Required fields are marked *