qbasic

Printing The Lowest Number From An Array Using DO UNTIL LOOP


I'm writing a QBasic program that will receive the marks of 10 students using DO UNTIL loop and compute the lowest mark, but my program always seems to freeze when I run it and enter the 10 students marks.

I tried everything that I know to, but it still freezes anyway.

Below is my code:

DIM arr(10) AS INTEGER
DIM low AS INTEGER
DIM x AS INTEGER

CLS
x = 0
DO UNTIL x >= 10
    INPUT "Enter Number: ", arr(x)
    x = x + 1
LOOP

low = arr(1)

DO UNTIL x >= 11
    IF arr(x) < low THEN
        low = arr(x)
    END IF
LOOP

CLS 

PRINT "All Marks Are:"
PRINT arr(x); " ";

PRINT
PRINT "The Lowest Number is: "; low

And I'm expecting results below:

All Marks Are:
54 32 59 43 90 43 12 4 54 35

The Lowest Number is: 4

Solution

  • Okay, I would change a couple things in your code. First of all,

    DO UNTIL x >= 10
        INPUT "Enter Number: ", arr(x)
        x = x + 1
    LOOP
    

    Why use a DO ... LOOP here? I'd opt for a FOR loop:

    FOR x = 1 to 10
      INPUT "Enter Number: ", arr(x)
    NEXT
    

    It's more conventional, shorter code, and overall cleaner.

    Secondly, your second DO ... LOOP has no way of exiting. Yeah, sure, it exits when x is greater than or equal to 11, but when's that going to happen? There's no redefining of x going on in your loop, so your loop is either infinite (if x starts out less than 11) or meaningless (if x is already 11 or greater). In this case, x will equal 10 at this point, so your code will, as you described, freeze.

    The parsing you're trying to do is unfortunately excessively complex in QBasic, but it is possible. For clarity, at the top of your program define TRUE and FALSE:

    CONST TRUE = 1
    CONST FALSE = 0
    

    Then when you come to the place where you want to parse for the smallest value, do something along these lines:

    finished% = TRUE 'I start by defining as TRUE and define as FALSE if I find
                     'a value which is smaller than the currently tested value.
    
    CurTest% = 1 'This represents the array element which I am currently testing.
                 'It will change only when the program finds a value smaller than
                 'the one it is currently testing.
    
    DO
      finished% = TRUE
      FOR i = CurTest% + 1 TO 10
        IF arr(i) < arr(CurTest%) THEN
          finished% = FALSE
          CurTest% = i
          EXIT FOR
        END IF
      NEXT i
    LOOP UNTIL finished% = TRUE
    
    'The loop will only complete once it has gone through a complete FOR...NEXT
    'without finding a smaller value.
    
    PRINT "The smallest value is:"; arr(CurTest%)
    

    *N.B.: Code is untested; there may be quirks / bugs.

    Hope this helps!