0

Assembly Language

Write a program that computes (n)(n+1)/2. It should read the value “n” from the user. Hint: you can compute this formula by adding up all the numbers between one and n.

I have a challenge in writing the above code in HLA. I have managed to get the following

program printing_n_Numbers;
    #include("stdlib.hhf");
    static
        n:int32;
        i:int32;
begin printing_n_Numbers;
    stdout.put("Enter n: ");
    stdin.get(n);
    mov(0,ecx)
    stdout.put("printing ",n," Numbers ",nl);
    for(mov(0,eax);eax<=n;add(1,eax)) do
        for(mov(0,ebx);ebx<eax;add(1,ebx)) do
            ecx = add(eax,ebx);
            stdout.put("N was = ");
            stdout.puti32(exc);
            stdout.newln();
        endfor;
    endfor;
end printing_n_Numbers;  

when i input a number like 6, the output is

Enter n: 6
printing 6 Numbers
N was = 1
N was = 2
N was = 3
N was = 4
N was = 5
N was = 2
N was = 4
N was = 6
N was = 3
N was = 6
N was = 4
N was = 8
N was = 5
N was = 6

How would i code it to output the sum of numbers enterd?

Community
  • 1
  • 1
Victor Omondi
  • 58
  • 2
  • 5
  • Create a new variable called "sum", initialize it to 0, then add the numbers 1 to n to "sum", then display "sum". – rcgldr Mar 01 '19 at 20:15
  • 1
    Does HLA not include multiply or divide operations? If multiply and divide are supported, there is no need to sum the numbers 1 to n, the program can just compute the product (n)(n+1) then divide by 2. It's not clear if the "hint" is just a comment on what the formula is used for, or if it is intended as part of the assignment for you to sum up the numbers 1 to n. – rcgldr Mar 01 '19 at 20:19
  • @rcgldr: HLA is/was intended to be usable for real programs, and supports all x86 instructions (at at least ones that existed at the time it was written). So yes it supports `intmul(edx, eax)` for example. (Apparently the actual `imul` and `mul` HLA mnemonics are only for the one-operand widening form with EDX:EAX as a destination (but it allows implicit or explicit). http://www.plantation-productions.com/Webster/www.artofasm.com/Windows/HTML/IntegerArithmetic.html). That sounds helpful, but when you're trying to think about what the machine can do it's probably more confusing. – Peter Cordes Mar 02 '19 at 04:08

1 Answers1

0

Solved

After multiple changes the program worked. this is how i modified it

mov(0,ecx);
    stdout.put("You Have Entered: ",n,nl);
    for(mov(0,eax);eax<=n;add(1,eax)) do
        add(eax,ecx);
    endfor;

In order to print the sum, this is the code

stdout.puti32(ecx); 

I used stdout.puti32 to convert the hexadecimal to the original decimal number system

Community
  • 1
  • 1
Victor Omondi
  • 58
  • 2
  • 5