| Loops: while | ||||||||||||
| $s1 | i | |||||||||||
| If statement uses branch instruction. | $s2 | j | ||||||||||
| What about loops? | $s3 | k | ||||||||||
| Example: | ||||||||||||
| while ( <cond> ) { | L1: if ( <cond> ) { | |||||||||||
| <while-body> | <while-body> | |||||||||||
| } | goto L1 ; | |||||||||||
| } | ||||||||||||
| If condition is true, execute body and go back, otherwise do next statement. | ||||||||||||
| while ( i < j ) { | L1: if ( i < j ) { | |||||||||||
| k++ ; | k++ ; | |||||||||||
| i = i * 2 ; | i = i * 2 ; | |||||||||||
| } | goto L1 ; | |||||||||||
| } | ||||||||||||
| L1: | bge $s1, $s2, DONE | # branch if ! ( i < j ) | ||||||||||
| addi $s3, $s3, 1 | # k++ | |||||||||||
| add $s1, $s1, $s1 | # i = i * 2 | |||||||||||
| j L1 | # jump back to top of loop | |||||||||||
| DONE: | ||||||||||||