#sum of 1 to 5 example, but using a while loop
int i = 1;
int sum = 0;
while (i <= 5) {
    sum += i;
    i++;
}

.data
msg: .asciiz "Sum = "

.text
.globl main
main:
    li $t0, 1          # i = 1
    li $t1, 0          # sum = 0

while_loop:
    bgt $t0, 5, end    # while (i <= 5): if i > 5, exit loop

    add $t1, $t1, $t0  # sum += i
    addi $t0, $t0, 1   # i++

    j while_loop       # repeat the loop

end:
    # print "Sum = "
    li $v0, 4
    la $a0, msg
    syscall

    # print sum
    move $a0, $t1
    li $v0, 1
    syscall

    # exit
    li $v0, 10
    syscall
    
    #Initialization: li $t0, 1 for i, li $t1, 0 for sum.

Condition check: bgt $t0, 5, end means "exit if i > 5", which is the inverse of i <= 5.

Loop body: adds i to sum, then increments i.

Loop control: uses j while_loop to jump back.


#C Equivalent (do...while)
int i = 1;
int sum = 0;
do {
    sum += i;
    i++;
} while (i <= 5);

.data
msg: .asciiz "Sum = "

.text
.globl main
main:
    li $t0, 1          # i = 1
    li $t1, 0          # sum = 0

do_loop:
    add $t1, $t1, $t0  # sum += i
    addi $t0, $t0, 1   # i++
     li $t2, 5
    slt $t3, $t2, $t0       # if 5 < i ⇒ i > 5, $t3 = 1
    beq $t3, $zero, do_loop # if i <= 5 ⇒ $t3 == 0 ⇒ repeat loop


    #ble $t0, 5, do_loop # while (i <= 5): if i <= 5, repeat

end:
    # print "Sum = "
    li $v0, 4
    la $a0, msg
    syscall

    # print sum
    move $a0, $t1
    li $v0, 1
    syscall

    # exit
    li $v0, 10
    syscall

Explanation:

    do_loop label marks the start of the loop body.

    The body runs unconditionally once (just like in C).

    At the end of the body, we use ble (branch if less than or equal) to check if i <= 5. If true, it jumps back to do_loop.


