'=========================================================================== ' Subject: ADD SHOWING WORK Date: 11-24-98 (22:29) ' Author: Jeff Connelly Code: QB, QBasic, PDS ' Origin: shellreef@email.msn.com Packet: ALGOR.ABC '=========================================================================== ' Created:10-16-98 ' By Jeff Connelly ' Adding, ****SHOWING WORK!**** ' These constents can be changed to change the color scheme CONST colCarry = 9 ' Carry color CONST colNum = 4 ' Color of numbers except result CONST colResult = 15 ' Color of sum CONST colDiv = 7 ' Color of divider (----- thing) CLS COLOR 14: PRINT "ADD SHOWING WORK" COLOR 8: PRINT "by Jeff Connelly" PRINT COLOR 7 INPUT "Numbers (a+b): ", s$ IF (INSTR(s$, "+") = 0) THEN PRINT "Syntax error!" PRINT "Enter 'a+b', where a and b are numbers" PRINT "Example: 1+1" END END IF ' The string S$ has two numbers in it delimited by a plus sign '+' a$ = LTRIM$(STR$(VAL(MID$(s$, 1, INSTR(s$, "+"))))) b$ = LTRIM$(STR$(VAL(MID$(s$, INSTR(s$, "+"))))) ' Add leading zeros if needed IF (LEN(a$) > LEN(b$)) THEN b$ = STRING$(LEN(a$) - LEN(b$), "0") + b$ ELSEIF (LEN(b$) > LEN(a$)) THEN a$ = STRING$(LEN(b$) - LEN(a$), "0") + a$ END IF ' Main adding loop. Using LEN(A$) or LEN(B$) does not matter, they should ' be the same because of the extra zeros added. Notice it goes backwards, ' that is the way math is. FOR i = LEN(a$) TO 1 STEP -1 ' Get the digits in both numbers at position I and add them together, ' also adding the carry (may be zero). res = VAL(MID$(a$, i, 1)) + VAL(MID$(b$, i, 1)) + carry ' Convert result to string because it is easier to work with res$ = LTRIM$(STR$(res)) IF (LEN(res$) = 2) THEN ' carry needed, greater than 9 ' The length of the sum of the two digits is greater than 9, there- ' fore we need to carry. ' First digit is the digit to carry, and the second is the value ' to prepend to the result. sum$ = MID$(res$, 2, 1) + sum$ carry = VAL(MID$(res$, 1, 1)) ' Add the carry to the list of carrys carrys$ = LTRIM$(STR$(carry)) + carrys$ ELSE ' The length of the result is only one digit, no carry needed. carry = 0 ' Put a space in the list of carrys carrys$ = " " + carrys$ ' Prepend to result sum$ = res$ + sum$ END IF NEXT ' The last carry, if any, was not used, so use it now IF (carry) THEN sum$ = LTRIM$(STR$(carry)) + sum$ ' Indent for cosmetic purposes a$ = " " + a$ b$ = "+" + b$ sum$ = " " + sum$ ' Finally, print the result COLOR colCarry: PRINT carrys$ COLOR colNum: PRINT a$: PRINT b$ COLOR colDiv: PRINT STRING$(LEN(a$) + 1, "-") COLOR colResult: PRINT sum$ COLOR 7 ' See if the answer is actually correct IF (VAL(sum$) <> VAL(a$) + VAL(b$)) THEN PRINT "Error! Result is incorrect!" PRINT "The correct sum is: " + LTRIM$(STR$(VAL(a$) + VAL(b$))) PRINT "If a number you entered contained a '+', '-', '.' or another" PRINT "non-digit character, the result may be wrong. Extreamly large" PRINT "numbers are repersented using an exponent, and fail." END IF