Page 297 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 297
274 Chapter 9 Implementation of C Procedures
9.4 Loop Statements, Arrays, and Structs
In this section, we show how statements within a loop can be repeated until a condition
is met, governed by an expression much like the expressions of the conditional
statements. First, we consider an accumulation of variables incremented or decremented
in the loop, in different loop constructs. Then we discuss array elements accessed using
indexes. Struct elements are accessed using AND, OR, and shift operations. We will
access a two-dimensional array using indexes in for loops and a struct in a do
while loop.
The for and while statements test the condition before the loop is executed and
are useful if, for example, a loop may have to be done 0 times. The do while
statement performs the statement once before it tests the condition. See Figure 9.10.
int i;
main(){ int j, k;
for(j = k = 0; j != i; j++) k += j;
while(j != 0) k += —j;
do k += j—; while (j != i);
}
a. A C Program
* 3: for(j = k = 0; j != i; j++) k += j;
00000802 C7 CLRB
00000803 87 CLRA
00000804 B745 TFR D,X
00000806 2005 BRA *+7 ;abs = 080D
00000808 1AE6 LEAK D f X
0000080A C30001 ADDD #1
0000080D BC0800 CPD $0800
00000810 26F6 BNE *-8 ;abs = 0808
* 4: while(j != 0) k += —j;
00000812 2005 BRA *+7 ;abs = 0819
00000814 830001 SUBD #1
00000817 1AE6 LEAK D,X
00000819 0474F8 TBNE D,*-5 ;abs = 0814
* 5: do k += j—; while (j != i);
0000081C 1AE6 LEAK D,X
0000081E 09 DEX
0000081F BC0800 CPD $0800
00000822 26F8 BNE *-6 ;abs = 081C
00000824 3D RTS
b. Assembly Language developed from Part (a)
Figure 9.10. For, While, and Do While Loops