# Number of iterations in nested loop (8051)

Let's say we have this program:

    MOV  R5, #4
H2: MOV  R6, #10
H1: DJNZ R6, H1
DJNZ R5, H2

1. After moving the data to the registers, microcontroller executes DJNZ R6, H1, which decrements R6 register x= 10 times.

2. In DJNZ R5, H2 we're charging 10 onto R6 again. Meaning that for every decrement on R5, we iterate 10 times, meaning that in total there are y= 40 iterations.

Why in every tutorial I've seen, the total number of iterations is of y=40 and not the actual total one x+y=50?

• y= 40 already contains the x= 10 ... your x+y=50 is same as x + 4x = 50 Commented Mar 21 at 3:35

Do you agree that regardless of what's inside it, the outer loop gets executed y = 4 times?

You've already stated that the inner loop executes x = 10 times.

So, for every iteration of the outer loop, you get 10 iterations of the inner loop. And therefore, the total number of iterations is y × x = 40.

In any case, x + y is not 50.

• First, thanks for the reply. Secondly, why do we ignore what's inside the outer loop? That's what I don't get, because the main difference between this reasoning and mine is the fact that I consider what's happening inside outer loop!
– Agus
Commented Mar 21 at 14:22
• Another thing I'm trying to understand is why, if this is a nested loop, do we start by executing the inner loop first? I mean, you start by reasoning what's happening in the outside loop first, so why shouldn't we make a SJMP to that instruction first? I mean, doing an SJMP HERE between first and third instruction and tagging HERE: DJNZ R5, H2
– Agus
Commented Mar 21 at 14:29
• @Agus It is not ignored. The outer loop executes 4 times, inner loop 10 times. What line or part of the code is unclear? If you understand for loops in C or Python or other language, do you understand nested for loops? Commented Mar 21 at 17:41

Write:

            MOV  R5, #4     ;; a
H2:     MOV  R6, #10    ;; b
H1:     DJNZ R6, H1     ;; c
DJNZ R5, H2     ;; d


The effect is similar to the following pseudo-C, where I added annotations:

    #include <stdio.h>
int main(void) {
unsigned char R5, R6;
putchar('a'), R5 = 4;
H2:     putchar('b'), R6 = 10;
H1:     putchar('c'); if (--R6 != 0) goto H1;
putchar('d'); if (--R5 != 0) goto H2;
fflush(stdout);
return 0;
}


Upon compilation and execution, it produces the output:

    abccccccccccdbccccccccccdbccccccccccdbccccccccccd


That's 1 "a", 4 "b", 40 "c" and 4 "d". The original is doing the first instruction once, the second and fourth instruction four times each and the third instruction forty times.