views:

307

answers:

2

Hi.

I've encountered problems with assembler code. I'm a newbie to assembler, so it seems difficult for me to solve it myself.

The task is: "To find minimal and maximal elements of the array."

All I've already done is searching for maximal element. I can't find out, how to make check for the minimal element and where I should put such verification. Or, probably, I should loop through elements second time after finding maximal element?

Code:

#include <conio.h>
#include <stdio.h>
#include <iostream.h>
void main() {
   int  N = 10, i;
   clrscr();
   int a[] = { 1, 4, -6, 12, -25, 10, 3, -4, 15, 7}, MAX, MIN, RESULT;

    __asm{
    mov cx, N
    lea si, a
    lodsw
    mov bx, ax
    mov dx, ax
    dec cx }
    m:
       __asm{
     lodsw
     cmp dx, ax
     jge m1
     mov dx, ax
       }
    m1:
       __asm{
       loop m
       mov MAX, dx
    }

cout << "Max = " << MAX;
//cout << "Min = " << MIN;
getch();
}
+3  A: 

What happens if you replace "jge" with "jle"? Try it and see.

Wayne Conrad
Result will be equal '-25' - the minimal value of the array.
Alex
Very good. Now you have two loops, one to compute the min, and one to compute the max. What would you have to do to combine them into one loop? Hint: The loop you have is already initializing two registers (bx and dx) but currently only using one of them.
Wayne Conrad
A: 

If it's interesting to someone, here is the solution for my question(I found out it today with help of my tutor):

#include <conio.h>
#include <stdio.h>
#include <iostream.h>
void main() {
   int  N = 10, i;
   clrscr();
   int a[] = { 1, 4, -6, 12, -25, 10, 3, -4, 15, 7}, MAX, MIN, RESULT;

    __asm{
      mov cx, N
      lea si, a
      lodsw
      mov MIN, ax
      mov MAX, ax
      dec cx
    }
    m:
     __asm{
       lodsw
       cmp MIN, ax
       jle m1
       mov MIN, ax
       jmp m2
    }
    m1:
     __asm{
       cmp MAX, ax
       jge m2
       mov MAX, ax
    }
    m2:
     __asm{
       loop m;
    }

cout << "Max = " << MAX << "\n";
cout << "Min = " << MIN;
getch();
}

Algorithm: if cmp MIN, ax has negative result, it means ax is greater, than MIN. So script jumps to m1 label to compare ax value with MAX. When cmp MIN, ax returns positive value, scripts assigns value of ax register to MIN variable and after that jumps to the m2 label to decrement loop counter. Algorithm of finding maximal value works similarly(label m1).

Alex