Have a problem summing numbers in Rexx (Creating Luhn Algorithm)

414 Views Asked by At

Hello I am new to Rexx and working on creating the luhn algorithm in a subroutine get an the error when trying to add the digit to the variable to hold the sum in each iteration of my loop. The code runs with no error when I remove 'sumOfNum = sumOfNum + numToSum' statement.

inspecting 7459274623941467 108 +++ sumOfNum = sumOfNum + numToSum 41 +++ call INSPECT IRX0041I Error running CCVIEW, line 108: Bad arithmetic conversion READY

INSPECT:
  say 'inspecting' cc_digits
  up = 1
  flag = 0  /* for every other digit */

  /* Loop to assess each digit in cc_digits */
  do i = 0 to 16 by 1

    /* Identify Numbers to sum */
    digit = SUBSTR(cc_digits,up,1) /* Returns digit */
    up = up + 1                    /* for next digit */

    /* to use only every other number */
    if (if flag = 0) then 
      do
        numToSum = 0          
        numToSum = digit * 2
        flag = 1
      end

    /* Skip this digit */
    else
      do
        Flag = 0
      end

    /*if digit > 9 sum digits of digit */
    if (numToSum > 9) then
      do
        digit1 = SUBSTR(cc_digits,1,1)
        digit2 = SUBSTR(cc_digits,2,1)
        numToSum = digit1 + digit2          
      end

    /* to accumulate sum */
    sumOfNum = sumOfNum + numToSum
  end
RETURN
1

There are 1 best solutions below

0
On BEST ANSWER

The problem is multifold.

  1. You do not initialze variable sumOfNum, and so it contains "SUMOFNUM" when referenced in the addition at the bottom. Therefore "bad arithmetic vonverison".
  2. Your if statement if (if flag = 0) then does not do what you think it would. REXX resolves this to if ( "IF 0" = 0 ) then..., or if ( "IF 1" = 0 ) then..., depending on the content of variable flag. The expression inside the parenthesis is always false, irrespective of the content of variable flag.
  3. You do not verify the variable cc_digitsreally contains digits, only.
  4. Your main loop executes 17 times, but it seems you pass on a 16 digit number, only.

I suggest you start using trace ?i do debug your REXX. This will show each line with the intermediate steps (the "i" in the trace command), will show the result of the statement execution, then waits for you to hit enter before executing the next statement (the "?" in the trace command).

Note that you can type any complete REXX statement when "trace" is waiting for you, and this is run before then next statment. You can show content of variables, e.g. say numToSum, or run any other REXX statement in the curent context of the programm.