8085 program to find the element that appears once

Prerequisite – Find the element that appears once in an array where every other element appears twice
Problem – Given 11 numbers, write an assembly language program to find the element that appears once where 5 numbers appear twice and one element appears once.

Examples:

Input : [01H, 02H, 09H, 01H, 01H, 02H, 0AH, 01H, 09H, 03H, 03H]
Output : 0AH
Every number appears even number of times, except 0AH which appears only once.

Algorithm:
Use XOR.
XOR of all the elements will give the number that appears once. This is because XOR of a number with itself is 0 and XOR of a number with 0 is the number itself.



^ => XOR

res = 01H ^ 02H ^ 09H ^ 01H ^ 01H ^ 02H ^ 0AH ^ 01H ^ 09H ^ 03H ^ 03H

Since XOR is associative and commutative :
res = 0AH ^ (01H ^ 01H) ^ (01H ^ 01H) ^ (02H ^ 02H) ^ (03H ^ 03H) ^ (09H ^ 09H) 
    = 0AH ^ 0 ^ 0 ^ 0 ^ 0 ^ 0
    = 0AH ^ 0
    = 0AH

Steps:

  1. Load the address of the first number in the HL register pair
  2. Initialize the register C with 0BH because we have to traverse 11 elements. It acts as a counter
  3. Initialize the accumulator with 0
  4. Take XOR of the value present at the address stored in the HL register with the accumulator and increment the address in the HL register
  5. Repeat step 4 for the rest of the 10 elements
  6. Store the value of the accumulator in 201DH (arbitrary)

201DH contains the answer.

ADDRESS LABEL MNEMONIC
2000H LXI H, 2012H
2001H
2002H
2003H MVI A, 00H
2004H
2005H MVI C, 0BH
2006H
2007H LOOP MOV B, M
2008H XRA B
2009H INX H
200AH DCR C
200BH JNZ LOOP
200CH
200DH
200EH STA 201DH
200FH
2010H
2011H HLT



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.