09-30-25 Lab 10

Loop Example (1) - Factorial

C Code:

#include <stdio.h>

long factorial_do(long n) {
    long result = 1;
    do {
        result *= n;
        n -= 1;
    } while (n > 1);
    return result;
}

int main() {
    long n = 5;
    long res = factorial_do(n);
    printf("factorial(%ld) = %ld\n", n, res);
    return 0;
}

Factorial (do-while) assembly code:

    .data
msg:
    .string "factorial(5) = %ld\n"
    .text
    .globl factorial_do

factorial_do:
    movq $1, %rax           # result = 1
.Lloop
    imulq %rdi, %rax        # result *= n
    subq $1, %rdi           # n -= 1
    cmpq $1, %rdi
    jg .Lloop
    ret

    .globl _start
_start:
    movq $5, $rdi           # argument n = 5
    call factorial_do       # call factorial_do
    movq %rax, %rsi         # move result into printf arg2
    movq $msg, %rdi         # printf format string
    movq $0, %rax           # printf needs AL = # of vector registers used
    call printf

    # exit(0)
    movq $60, %raxxorq %rdi, %rdi
    syscall                 # exit the program

What is the difference between while and for?

Do-while

Compiling AT&T syntax x86 assembly:

arch -x86_64 clang -m64 hello.s -o hello

Factorial (while) assembly code:

    .data
msg:
    .string "factorial(5) = %ld\n"
    .text
    .globl factorial_while

factorial_while:
    movq $1, %rax           # result = 1

.Lcheck:
    cmpq $1, %rdi           # compare n add 1
    jle .Ldone              # if (n <= 1) -> exit loop
    imulq %rdi, %rax        # result *= n
    subq $1, %rdi           # n -= 1
    jmp .Lcheck             # repeat

.Ldone:
    ret                     # return result in %rax

    .globl _start
_start:
    movq $5, $rdi           # argument n = 5
    call factorial_do       # call factorial_do
    movq %rax, %rsi         # move result into printf arg2
    movq $msg, %rdi         # printf format string
    movq $0, %rax           # printf needs AL = # of vector registers used
    call printf

    # exit(0)
    movq $60, %rax
    xorq %rdi, %rdi
    syscall                 # exit the program

Loop Example (2)

C Code:

#include <stdio.h>
// while loop
long sum_while(long n) {
	long sum = 0;
	while (n > 0) {
		sum += n;
		n--;
	}
	return sum;
}

// do...while loop
long sum_do(long n) {
	long sum = 0;
	if (n > 0) {
		do {
			sum += n;
			n--;
		} while (n > 0)
	}
	return sum;
} 

// for loop