QBASIC – Sum of n natural numbers

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

' Program to find sum of numbers from 1 to n
CLS
sum = 0
INPUT "Enter the value of n "; n
FOR i = 1 TO n
  sum = sum + i
NEXT i
PRINT "Sum of numbers from 1 to ";n;" is ";sum
END

Explanation:

If you remember in the program to display the sum of numbers from 1 to 5, the loop runs from 1 to 5 and we are calculating the sum using sum = sum + i inside the loop. However, in this case, the loop runs from 1 to n where n is the user input number.

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 *