## Sum of n Natural Numbers

Back to Programming

### Description

Here, the program is written to find the sum of ‘n’ natural numbers. Natural numbers are the positive integers. The numbers are taken as input. While taking input, the number is checked whether it is a positive integer or not, if not then another positive number is taken as input. Then using a ‘for’ loop the numbers are added.

For example, if the number of elements is 2 and the given inputs are: 1, 2.

Then the sum will be: 1+2=3

### Algorithm

INPUT: The number of elements and the numbers to be added

OUTPUT: Sum of the given numbers

PROCESS:

Step 1: [Taking the input]

For i=0 to n-1 repeat

If arr[i]≤0 then

Print “Enter a positive integer”

Set i<-i-1

[End of ‘if’]

[End of ‘for’ loop]

Set sum<-0

For i=0 to n-1 repeat

Set sum<-sum+arr[i]

[End of ‘for’ loop]

Print "The sum of the numbers: sum"

Step 3: Stop.

## TIME COMPLEXITY:

for(i=0;i<n;i++)-------------------------------------------O(n)

{

sum=sum+arr[i];

}

The time complexity of this program is O(n) where ‘n’ is the number of elements to be added.

## SPACE COMPLEXITY:

The space complexity of this program is O(n) where ‘n’ is the number of elements to be added