sum of n natural numbers code example

Example 1: sum of n natural numbers

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	int sum=0;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		sum+=i;
	}
		cout<<sum<<" ";
	cout<<endl;
	return 0;
}

Example 2: sum of n natural numbers in python

# Sum of natural numbers up to num

num = 16

if num < 0:
   print("Enter a positive number")
else:
   sum = 0
   # use while loop to iterate until zero
   while(num > 0):
       sum += num
       num -= 1
   print("The sum is", sum)

Example 3: sum of all n integers

Sum of n integers 1 + 2 + 3 + ... + n = n * (n + 1) / 2

Example 4: formula for sum of n numbers

Sum of the First n Natural Numbers. We prove the formula 1+ 2+ ... + n = n(n+1) / 2, for n a natural number

Example 5: sum of n natural numbers in c

int addNumbers(int n)
{
    int count, sum = 0;

    for(count=1; count <= n; count++)
    {
        sum = sum + count;
    }
  
    return sum;
}