QBASIC WHILE Loop – Print numbers from 1 to 5

Below is the QBASIC program to display the numbers from 1 to 5 using WHILE…WEND looping statement. The main objective of the example is to understand the syntax of WHILE…WEND loop.

' Program to print numbers from 1 to 5
CLS
i = 1
WHILE i <= 5 
  PRINT i
  i = i + 1
WEND
END

Explanation:

Unlike FOR loop where the value of the loop variable is initialized in the looping statement, the loop variable is initialized before the WHILE loop starts. As can be seen in the example, i is initialized to 1. The WHILE statement is followed by a condition to terminate the loop. In the example, the condition is the loop variable i is less than or equal to 5 (i <= 5); meaning the loop will terminate if the value of i is greater than 5.

Next line after while statement is a print statement to display the value of i. Then, the value of i is incremented by 1 using the expression i = i + 1. As WHILE loop doesn’t increment or decrement the value of the variable by itself unlike FOR loop, this step is a must to increment or decrement the value of the variable based on the requirements.

Finally, the WEND statement; functions like the NEXT statement in FOR loop to send the cursor to the WHILE statement and run the loop again. WHILE statement checks for the condition and run the loop if the condition is satisfied or terminates the loop if the condition fails.

Leave a Comment

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