# Write a program to find sum of n natural number in O(1)

## Write a  program to find sum of n natural number in O(1)

Given a number , write a program to find the sum of natural numbers up to n . For this we will use a simple formula .

Sum of natural number up to n :- (n*(n+1)) /2

Sample input :

`10`

Sample output:

`55`

## Write a  program to find sum of n natural number in O(1)

The objective of the code is to find the sum of n natural numbers in O(1) time  . Value of n is given by user .

Code(C):-

#include<stdio.h>
int main()
{
int n,sum;
printf("Enter the number ");
scanf("%d",&n);
sum=(n*(n+1))/2;
printf("sum is %d",sum);
}

Output:-

Enter the number
10
sum is 55

Code(C++):-

#include <iostream>
using namespace std;
int main()
{
int n,sum;
cout<<"Enter the number ";
cin>>n;
sum=(n*(n+1))/2;
cout<<"sum is "<<sum;
return(0);
}

Output:-

Enter the number
10
sum is 55

Code(Python):-

print("Enter the number ")
n=int(input())
sum=(n*(n+1))//2;
print(f"sum is {sum}")

Output:-

Enter the number
10
sum is 55

Sum of n natural numbers by using loop :- click here

### Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-
iMocha coding Questions:-
Tech Mahindra coding questions:-
Unthinkable Solutions coding questions:-