header

Week 11 Homework

Due Apr 3

Assembly Language Programs

Problem 3

The following program implements and tests a method that finds the product of two non-negative integer values:

.constant
    OBJREF 0
    N1 20
    N2 30
.end-constant

.main
    .var
        p
    .end-var

    ldc_w OBJREF
    ldc_w N1
    ldc_w N2
    invokevirtual Product
    istore p
    halt
.end-main

.method Product (f1, f2)
    .var
        prod
    .end-var

    bipush 0
    istore prod          // prod = 0
TOP:                     //
    iload f1             // while (f1 > 0)
    ifeq END             // {
    iload prod           //     prod = prod + f2;
    iload f2             //
    iadd                 //
    istore prod          //
    iinc f1 -1           //     f1 = f1 - 1;  
    goto TOP             // }
END:                     //
    iload prod           // return prod;
    ireturn
.end-method

The product algorithm, initializes the product at zero and then adds the value of f2 to the product f1 times. Your job is to enhance the Product method so that

  1.  it will work correctly even if f1 and/or f2 are negative.
  2. the counter in the loop will be the smaller of the absolute value of f1 and the absolute value of f2.

We discussed the logic for these modifications in class last Wednesday:

int Product(int f1, int f2)
{
    int prod;
    int is_neg;   // 0 => false, anything else => true

    is_neg = 0;
    if (f1 < 0)
    {
        f1 = - f1;
        is_neg = is_neg + 1;
    }
    if (f2 < 0)
    {
        f2 = -f2;
        is_neg = is_neg - 1;
    }
    if (f2 < f1)
    {
        swap f1 and f2;   //  as in H10P1.jas
    }

    // At this point, f1 and f2 are both positive, f1 <= f2, and
    // is_neg indicates whether the product should be negative.

    find the product of f1 and f2 using the basic algorithm
    given at the top of this page.

    if (is_neg != 0)
    {
        product = -product;
    }

    return product;
}

I should be able to modify the values of the constants N1 and N2 and get the correct product. Submit your program as "H11.JAS".