diff --git a/src/task2_3.asm b/src/task2_3.asm new file mode 100644 index 0000000000000000000000000000000000000000..c4e604ae30c444182b9a505dc07220802c482183 --- /dev/null +++ b/src/task2_3.asm @@ -0,0 +1,107 @@ +section .data + sum_msg db 'The sum is: %d', 0 + newline db 0xA, 0 + start_prompt db 'Enter the start index (0-99): ', 0 + end_prompt db 'Enter the end index (0-99): ', 0 + error_msg db 'Error: Invalid range!', 0 + +section .bss + array resd 100 ; Reserve space for 100 integers + sum resd 1 ; Reserve space for the sum + start_index resd 1 + end_index resd 1 + +section .text + extern printf, scanf + global asm_main + +asm_main: + ; Initialize the array with values from 1 to 100 + mov ecx, 100 + lea esi, [array] + mov eax, 1 +init_loop: + mov [esi], eax + add esi, 4 + inc eax + loop init_loop + + ; Prompt the user to input the start index + push start_prompt + call printf + add esp, 4 + + ; Read the start index + lea eax, [start_index] + push eax + push index_format + call scanf + add esp, 8 + + ; Prompt the user to input the end index + push end_prompt + call printf + add esp, 4 + + ; Read the end index + lea eax, [end_index] + push eax + push index_format + call scanf + add esp, 8 + + ; Validate the range + mov eax, [start_index] + mov ebx, [end_index] + cmp eax, 0 + jl print_error + cmp eax, 99 + jg print_error + cmp ebx, 0 + jl print_error + cmp ebx, 99 + jg print_error + cmp eax, ebx + jg print_error + + ; Calculate the sum of the elements within the specified range + mov ecx, ebx + sub ecx, eax + inc ecx + lea esi, [array] + mov edx, eax + shl edx, 2 ; Multiply start index by 4 for correct offset + add esi, edx + xor eax, eax ; Clear eax to use it as the sum +sum_loop: + mov edx, [esi] + add eax, edx + add esi, 4 + loop sum_loop + + ; Store the sum in the sum variable + mov [sum], eax + + ; Print the sum + push dword [sum] + push sum_msg + call printf + add esp, 8 + + ; Print newline + push newline + call printf + add esp, 4 + +exit_program: + ret + +print_error: + ; Print error message if the range is invalid + push error_msg + call printf + add esp, 4 + jmp exit_program + +section .rodata +index_format db '%d', 0