Here are practical questions on arrays in QBasic, covering both single-dimensional and multi-dimensional arrays, along with their solutions. These exercises are designed to help students understand and work with arrays effectively.
1. Sum of Elements in a Single-Dimensional Array
Q: Write a QBasic program to input 5 numbers into a single-dimensional array and calculate their sum.
Solution:
DIM arr(5) AS INTEGER
sum = 0
FOR i = 1 TO 5
INPUT "Enter a number: ", arr(i)
sum = sum + arr(i)
NEXT i
PRINT "The sum of the elements is: "; sum
2. Find the Largest Number in an Array
Q: Write a program to find the largest number in a single-dimensional array containing 10 elements.
Solution:
DIM arr(10) AS INTEGER
largest = -32768 ' Initialize with a very small value
FOR i = 1 TO 10
INPUT "Enter a number: ", arr(i)
IF arr(i) > largest THEN
largest = arr(i)
END IF
NEXT i
PRINT "The largest number is: "; largest
3. Search for an Element in an Array
Q: Write a program to search for a specific number in an array of size 7. If found, display its position; otherwise, display a message saying it is not found.
Solution:
DIM arr(7) AS INTEGER
INPUT "Enter the number to search for: ", target
found = 0
FOR i = 1 TO 7
INPUT "Enter a number: ", arr(i)
NEXT i
FOR i = 1 TO 7
IF arr(i) = target THEN
PRINT "Number found at position: "; i
found = 1
EXIT FOR
END IF
NEXT i
IF found = 0 THEN
PRINT "Number not found in the array."
END IF
These exercises introduce students to key concepts in array operations, including initialization, traversal, searching, and two-dimensional array manipulations like transposing a matrix.
No comments:
Post a Comment