# Example Templates

### sumOf3.asm reads 3 arguments and returns the sum using a stack

    READ X     /*read arg1*/
    PUSH       /*push arg1 onto stack*/
    LOAD X     /*ACC is arg1*/
    STACKW 0   /*tos-0=ACC*/

    READ X     /*read arg2*/
    PUSH       /*push arg2 onto stack*/
    LOAD X     /*ACC is arg2*/
    STACKW 0   /*tos-0=ACC*/

    READ X     /*read arg3*/
    STACKR 1   /*ACC=tos-1*/
    ADD X      /*ACC=ACC+X*/
    STORE X    /*X=ACC*/
    STACKR 0   /*ACC=tos*/
    ADD X      /*ACC=ACC+X*/
    STORE X    /*X=ACC*/
    WRITE X    /*output the sum as an integer*/
    POP        /*tos-*/
    POP        /*tos-*/
    STOP       /*end the program*/
    X 0        /*X is 0*/

### sum3nostack.asm Same as sumof3.asm but without a stack

    READ X     /*read arg1*/
    READ Y     /*read arg2*/
    READ Z     /*read arg3*/
    LOAD X     /*ACC is arg1*/
    ADD Y      /*add arg2 to the ACC*/
    ADD Z      /*add arg3 to the ACC*/
    STORE X    /*sum of the three arguments is ACC*/
    WRITE X    /*put sum to output as an integer*/
    STOP       /*stop the program*/
    X 0        /*arg1 is 0*/
    Y 0        /*arg2 is 0*/
    Z 0        /*arg3 is 0*/

### sumOfAny.asm reads ﬁrst argument and the reads as many arguments as the ﬁrst argument and returns the sum

    READ X          /*read X*/
    COPY Z X        /*Z = X*/
    LOOP1: LOAD X   /*Loop1 ACC = X*/
    BRZERO OUT1     /*jump to arg if ACC==0*/
    BRNEG OUT1      /*jump to arg if ACC<=0*/
    READ Y          /*read Y*/
    LOAD Y          /*ACC = Y*/
    PUSH            /*push onto topofstack*/
    STACKW 0        /*tos-0=ACC*/
    LOAD X          /*ACC = X*/
    SUB 1           /*ACC = ACC - 1*/
    STORE X         /*X = ACC*/
    BR LOOP1        /*jump to loop1*/

    OUT1: NOOP      /*Out1: nothing*/

    LOAD 0          /*ACC=0*/
    STORE Y         /*Y=ACC*/
    LOOP2: STACKR 0 /*ACC=stack[tos-0]*/
    ADD Y           /*ACC=ACC+Y*/
    STORE Y         /*Y=ACC*/
    POP             /*tos-*/
    LOAD Z          /*ACC=Z*/
    SUB 1           /*ACC=ACC-1*/
    BRZERO OUT2     /*jump to arg if ACC==0*/
    BRNEG OUT2      /*jump to arg if ACC<=0*/
    STORE Z         /*Z=ACC*/
    BR LOOP2        /*jump to loop2*/
    OUT2: NOOP      /*Out2: nothing*/
    WRITE Y         /*output the sum as an integer*/

    STOP            /*end the program*/
    X 0             /*X is 0*/
    Y 0             /*Y is 0*/
    Z 0             /*Z is 0*/