Assembly Code for Printing Numbers from 1 to 5 Three Times with New Lines
How to Write an Assembly Code that Prints Numbers from 1 to 5 Three Times on the Screen
This article explains how to write an assembly code for the x86 architecture that prints the numbers from 1 to 5 three times with each sequence of numbers separated by a new line. The code utilizes the NASM Netwide Assembler and is designed to run on a Linux environment.
Explanation of the Code
The example provided below is an assembly code that achieves the desired functionality:
Assembly Code (NASM Syntax)
section .data newline db 10, 0 ; New line character numbers db 1, 2, 3, 4, 5, 0 ; String of numberssection .text global _start_start: mov ecx, 3 ; Loop counter for 3 repetitionsprint_numbers: push ecx ; Save the loop counter on the stack mov eax, 4 ; Syscall number for sys_write mov ebx, 1 ; File descriptor 1: stdout mov edx, 5 ; Number of bytes to write lea esi, [numbers] ; Load address of numbers int 80h ; Call kernel mov edx, 1 ; Number of bytes to write for newline lea esi, [newline] ; Load address of newline int 80h ; Call kernel pop ecx ; Restore loop counter loop print_numbers ; Decrement ecx and loop if not zero mov eax, 1 ; Syscall number for sys_exit xor ebx, ebx ; Exit code 0 int 80h ; Call kernel
Explanation
Data Section
newline db 10, 0 - Contains the newline character (ASCII 10). numbers db 1, 2, 3, 4, 5, 0 - Contains the string representation of the numbers 1 to 5.Text Section
_start - The entry point of the program. mov ecx, 3 - Initializes the loop counter to 3 for three repetitions. print_numbers - Label marked the beginning of the loop. push ecx - Saves the loop counter on the stack. mov eax, 4 - Calls the Linux syscall for writing (sys_write). mov ebx, 1 - Specifies file descriptor 1 (stdout). mov edx, 5 - Sets the number of bytes to write. lea esi, [numbers] - Loads the address of the numbers array. int 80h - Calls the kernel. mov edx, 1 - Sets the number of bytes to write for a newline. lea esi, [newline] - Loads the address of the newline character. int 80h - Calls the kernel again. pop ecx - Restores the loop counter. loop print_numbers - Decrements the loop counter and loops if it is not zero. mov eax, 1 - Calls the Linux syscall for exiting (sys_exit). xor ebx, ebx - Sets the exit code to 0. int 80h - Calls the kernel to exit the program.Assembling and Running the Code
To assemble and run this code on a Linux system with NASM installed, follow these commands in the terminal:
nasm -f elf32 -o print_numbers.o print_
ld -m elf_i386 -o print_numbers print_numbers.o
./print_numbers
This will print the numbers from 1 to 5 three times, each sequence on a new line.
Conclusion
By following the provided assembly code and instructions, you can create a program that prints the numbers from 1 to 5 three times with each sequence separated by a new line. This example can be adapted and used in various scenarios to print sequences of numbers or other data in a loop.