8051 Program to arrange numbers in Descending Order:
8051 Program to arrange numbers in Descending Order is as follows:
MOV R4,#0AH AGAIN: MOV R3,#0AH MOV R0,#20H CLR C UP:MOV A,@R0 MOV R1,A INC R0 MOV A,@R0 SUBB A,R1 JC SKIP MOV A,@R0 DEC R0 MOV @R0,A MOV A,R1 INC R0 MOV @R0,A SKIP:DJNZ R3,UP DJNZ R4,AGAIN RET
Logic for 8051 Program to arrange numbers in Descending order:
For this program, we need two registers as counters. In order to arrange 10 numbers in descending order we need count value 10 x 10 ie 100. Similarly for n numbers count required will be n x n= n^2. Reason for that is, in one cycle only two adjacent numbers are compared. After comparison larger number is stored at higher memory location while small number is stored at lower memory location. Thus arranging adjacent numbers in descending order. But our goal is to arrange entire block in descending order so in order to compare every number with another it requires n x n cycles or comparison loops.
In above program a block of numbers is stored at location 20H-29H. First number is taken into Accumulator. Then the number is moved to register R1, this is done to fetch next number into accumulator. Second number is fetched into accumulator. Comparison is carried out between accumulator and contents of R1 (ie. first number). If first number is small it is stored in second location while the larger number is transferred at first location.
After the above process completes, one cycle is completed. In second cycle, number at second memory location and at third memory location are compared and action is taken. In third cycle number at third memory location and fourth are compared and action takes place. Similarly in further cycles the adjacent numbers are compared and action takes place.
Completion of 10 such cycles completes one batch. 10 such batches will be executed by the program. In case largest number is stored at 10th (last) memory location. It will take 10 such batches for it to reach first memory location. So execution of 10 batch cycles is essential.
Refer More Programs: