Basic Programing III - SS3 ICT Past Questions and Answers - page 2
In a FOR-NEXT loop, what does the NEXT statement do?
Ends the program
Ends the loop and proceeds to the next iteration
Prints the current value of the loop variable
Declares a new variable
Explain the purpose and syntax of the FOR-NEXT loop in BASIC.
The FOR-NEXT loop in BASIC is used for repetitive execution of a block of code. It allows you to specify a starting value, an ending value, and an optional step value for a loop variable. The loop variable is automatically incremented or decremented with each iteration until it reaches the ending value. The purpose of this loop is to simplify repetitive tasks by executing a set of statements multiple times.
Syntax:
vbnet
Copy code
FOR loop_variable = start_value TO end_value [STEP step_value]
' Code to be executed inside the loop
NEXT loop_variable
Describe the key differences between the FOR-NEXT and WHILE-END loops in BASIC
FOR-NEXT loop: It is used when you know the number of iterations in advance. You specify the starting and ending values, and the loop iterates within that range.
WHILE-END loop: It is used when you want to repeat a block of code based on a condition. The loop continues executing as long as the specified condition is true.
In summary, the main difference lies in control:
FOR-NEXT is controlled by a counter that increments or decrements a fixed number of times.
WHILE-END is controlled by a condition that can change within the loop.
How would you use the DIM statement to declare an array in BASIC? Provide an example
The DIM statement in BASIC is used to declare arrays by specifying the array's name and dimensions (size). Here's an example of declaring an array of 10 integers:
basic Copy code
DIM numbers(10)
This statement declares an array named numbers with 11 elements (0 to 10) to store integer values.
Write a BASIC program that calculates the sum of all even numbers from 1 to 50 using a loop
Here is a BASIC program that calculates the sum of even numbers from 1 to 50 using a FOR-NEXT loop:
basic Copy code
total = 0
FOR i = 2 TO 50 STEP 2
total = total + i
NEXT i
PRINT "Sum of even numbers from 1 to 50: "; total
This program initializes a total variable to 0 and then uses a FOR-NEXT loop with a step of 2 to iterate through even numbers from 2 to 50, adding them to the total variable. Finally, it prints the sum.