Question

I have made simple program which will calulate the sum of first n numbers(stored in varibale c1) and printf them on to the console.

When I run it ,works fine and give me the desired result.For example if I enter 4 from keyborad,it gives me 10 .

But now when I go through it manually ,find it should give a value 9 when I provide input as 4.

Is it code written fine?

section .bss
c1 db
section .data
x db "%d"
section .text
global main
extern printf
extern scanf
main:
mov ebx,1
mov eax,0
lea ecx,[c1]
push ecx
push x
call scanf
add esp,8
well_done:

inc ebx
add eax,ebx

cmp ebx,[c1]

jnz well_done
push eax
push message
call printf
add esp,8
ret
message:
db "sum is =%d",10,0

Edit:

section .text
global main
extern printf
main:
mov ebx,0
mov eax,0
well_done:

inc ebx
add eax,ebx
cmp ebx,4

jnz well_done
push eax
push message
call printf
add esp,8
ret
message:
db "sum is =%d",10,0

This above code gives the expected result for sum of first 4 numbers.

Was it helpful?

Solution

The problem is that scanf returns the number of items processed in eax, thereby overwriting the 0 you have put in there previously. Since you read 1 item, eax will be 1 and that explains why you get 10 when you run the code. You should move the mov eax, 0 down to after the scanf and start ebx from 0 too.

Other issues: you should use dd for your c1 because an integer is 4 bytes, not 1. You should also zero terminate your format string and put the message into the .data section as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top