Assembly - (NASM 32-bit) Printing a triangle of stars not working properly -
edit: problem solved. many mbratch.
my code outputs:
but should display this:
i think problem in innerloops can't fix it, works on first loop not on succeeding ones.
here's code:
innerloop1: ;;for(j=n-i;j>0;j--) mov bl, [i] sub byte [num], bl mov dl, [num] mov byte [j], dl cmp byte [j], 0 jle printstar mov eax, 4 mov ebx, 1 mov ecx, space mov edx, spacelen int 80h dec dl jmp innerloop1 printstar: mov eax, 4 mov ebx, 1 mov ecx, star mov edx, starlen int 80h innerloop2: ;;for(k=0;k<(2*i)-1;k++) mov al, [i] mul byte [two] dec al cmp byte [k], al jge printme mov eax, 4 mov ebx, 1 mov ecx, space mov edx, spacelen int 80h inc byte [k] jmp innerloop2 printme: mov eax, 4 mov ebx, 1 mov ecx, star mov edx, starlen int 80h mov eax, 4 mov ebx, 1 mov ecx, newline mov edx, newlinelen int 80h inc byte [i] jmp outerloop printspace: mov eax, 4 mov ebx, 1 mov ecx, space mov edx, spacelen int 80h
there lots of inefficiencies in code , more , concisely written. however, i'll address areas causing functional problem.
there couple of problems innerloop1
. modifying [num]
every time through loop. instead, want prior loop initializer j
. secondly, counting on value of dl
being intact through execution of loop, mov edx, spacelen
clobbers it, might call int 80h
. can correct this:
mov dl, [num] ; initialize j=n-i sub dl, byte [i] innerloop1: ;;for(j=n-i;j>0;j--) ; removed modification of 'num' here mov byte [j], dl cmp byte [j], 0 jle printstar mov eax, 4 mov ebx, 1 mov ecx, space push dx ; save dx mov edx, spacelen int 80h pop dx ; restore dx dec dl jmp innerloop1
in second inner loop (innerloop2
) relying on pre-initialized value of k
every time enter loop, no longer valid after first time loop encountered.. must initialize each time:
mov byte [k], 0 ; initialize k=0 innerloop2: ;;for(k=0;k<(2*i)-1;k++) mov al, [i] mul byte [two] dec al cmp byte [k], al jge printme
this makes code work. additional comments:
- you need cautious counting on values of registers , watch may altered
- you should not rely on pre-initialized declarations initialize loop variables or other data can vary matter. it's practice explicitly initialize value in code if you're going change regularly
- think how optimize code (make more concise , clear) works.
- be more consistent in variable usage. asm program used
num
n
defined valuen
, little confusing. - be consistent in code indentation , spacing. make easier read.
- when doing constructs, such
for
loops, try maintain consistent approach doing them every time. reduce chance of errors. example, manage loop variables in same or similar ways.
Comments
Post a Comment