Today we will see 8051 assembly program to find the sum of first N natural numbers. There are two ways to compute the sum of N natural numbers. We will go through one by one.

First method: It’s simple basic code. Let’s go through the algorithm.

__Algorithm:__- Start
- Store the value(N) up to which sum has to be found in a register(Ra)
- Initialize a register(Rb) to 1
- Enter the loop
- Add Rb and Accumulator register(A) and store the value in A
- Increment Rb
- Decrement and check whether Ra is zero
- If Ra is zero exit the loop and move value stored in A to destination register(Rd)
- Else, jump back and repeat the steps in loop

- Stop

here is an example code to find the sum of first 10 natural numbers.

__Code:__

1 2 3 4 5 6 7 8 9 10 11 12 |
ORG OOOOh LJMP main ORG 0x40h main: MOV R0,#0Ah ; N value MOV R1,#01h loop: ADD A,R1 INC R1 DJNZ R0, loop MOV R4,A ; Final result is stored in register R4 end |

Sum=n(n+1)/2

No need of algorithm. Example code is showed below

__Code:__
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ORG OOOOh LJMP main ORG 0x40h main: MOV R0,#0Ah ; N value MOV B,R0 INC R0 MOV A,R0 MUL AB ; n(n+1) MOV B,#02h DIV AB ; n(n+1)/2 MOV R4,A ; Final result is stored in register R4 end |

**[ Important:**When to use which algorithm?

Use the first method when your N value is small so that machine cycles reduces. And use the second method when N value is large so that you can get the result at a faster rate.

I have discussed both the methods in order to give you an idea about optimization. We will discuss more about optimization in future posts.

**]**