How to resolve the algorithm Function definition step by step in the Z80 Assembly programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Function definition step by step in the Z80 Assembly programming language

Table of Contents

Problem Statement

A function is a body of code that returns a value. The value returned may depend on arguments provided to the function.

Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Function definition step by step in the Z80 Assembly programming language

Source code in the z80 programming language

doMultiply:
;returns HL = HL times A. No overflow protection.
push bc
push de
    rrca                     ;test if A is odd or even by dividing A by 2.
    jr c, isOdd
        ;is even

        ld b,a
loop_multiplyByEvenNumber:
        add hl,hl           ;double A until B runs out.
        djnz loop_multiplyByEvenNumber
pop de
pop bc
ret

isOdd:
    push hl
    pop de                  ;de contains original HL. We'll need it later.
    ld b,a
loop_multiplyByOddNumber:
    add hl,hl
    djnz loop_multiplyByOddNumber
    add hl,de             ;now add in original HL for the leftover add.
pop de
pop bc
ret

  

You may also check:How to resolve the algorithm Terminal control/Cursor positioning step by step in the Blast programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Nemerle programming language
You may also check:How to resolve the algorithm Long multiplication step by step in the Vedit macro language programming language
You may also check:How to resolve the algorithm Inverted index step by step in the Ruby programming language
You may also check:How to resolve the algorithm Extend your language step by step in the PicoLisp programming language