Search code examples
cobol

Addition using cobol and loops


I am attempting to perform simple addition, but I'm not sure how to do this in cobol. I would like to add the last four years of tuition to a variable total_tuition. However, it will only add this once my first loop has been completed, hence giving me an addition of the last years tuition 4 times (which is not what I want). I completed the task in python to help clarify what I am trying to accomplish. Thank you!

   WORKING-STORAGE SECTION.
   01 tuition pic 9(5)v99.
   01 increase pic 9(5)v99 value 00000.05. 
   01 final_tuition pic 9(5)v99. 
   01 total_tuition pic 9(5)v99 value 00000.00. 
   01 temp pic 9(7)v99.
   01 num pic 9 value 1. 
   
   PROCEDURE DIVISION.
   MAIN-PROCEDURE. 
       display 'Please enter the tuition amount: '. 
       accept tuition. 
       
       perform aLoop 10 times.
       display 'Tuition after 10 years is: $', final_tuition. 
       perform bLoop with test after until num > 6. 

       display '4-year tuition in 10 years is: $', total_tuition. 
   STOP RUN.
       aLoop. 
           multiply tuition by increase giving temp . 
           add temp to tuition giving final_tuition. 
           set tuition to final_tuition.
       bLoop. 
           add final_tuition to total_tuition giving total_tuition. 
           add 1 to num. 
           display total_tuition. 

Python working solution:

n = 0
tuition = 10000
increase = .05
temp = 0
total = 0
final = 0
i = 0
while n < 10 : 
    temp = increase * tuition 
    final = tuition + temp
    tuition = final
    if n >= 6: 
        total = final + total 
        print(i, ") total", total)
        i = i + 1
    n = n+1 
print(final, total) 

Solution

  • In the Python version, you have an if statement. In the COBOL version, you have a second loop.

    Try this code:

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO-WORLD.
       DATA DIVISION.
       
       WORKING-STORAGE SECTION.
       01 tuition pic 9(5)v99 value 10000.
       01 increase pic 9(5)v99 value 00000.05. 
       01 final_tuition pic 9(5)v99. 
       01 total_tuition pic 9(5)v99 value 00000.00.
       01 temp pic 9(7)v99.
       01 num pic 9 value 0. 
       
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.              
           perform aLoop 10 times.
           display 'Tuition after 10 years is: $', final_tuition.     
           display '4-year tuition in 10 years is: $', total_tuition. 
       STOP RUN.
           aLoop. 
                multiply tuition by increase giving temp . 
                add temp to tuition giving final_tuition. 
                set tuition to final_tuition.
                if num >= 6 then
                    add final_tuition to total_tuition giving total_tuition
                end-if
                add 1 to num.
    

    Output

    Tuition after 10 years is: $16288.91
    4-year tuition in 10 years is: $60647.68