Sum of first n natural numbers in C# – Learn how to calculate Sum of First N natural Numbers using Mathematical formula and adding from 1 to N in sequential order. also Learn how to program in C# using Mathematical formula and adding in sequential order.
Natural Numbers are the Positive integers like 1,2,3……
1 is the starting Natural Number.
we have 2 methods to find sum of N natural Numbers
Method -1
To find the sum of first 5 natural numbers, we have solution like this 1+2+3+4+5 =15.
To find sum of N natural numbers , we have solution like this 1+2+….+N
Method -2
To compute This in Mathematical formula
SUM of N natural Numbers = N(N+1)/2
for Example to find first 5 natural numbers we can follow above for calculation.
SUM of 5 natural Numbers = 5(5+1)/2
= 5*6/2;
= 15
Sum of first n natural numbers in C#
below are the examples to calculate in Method -1 and in Method-2 process
Example1-C# program to find sum of N natural Numbers with Method-1 using for loop
using System;
class Program
{
static void Main(string[] args)
{
int i, num=20, sum = 0;
for (i = 1; i <= num; i++)
{
sum = sum + i;
}
Console.WriteLine("Sum of first" + num +
" natural numbers = " + sum);
}
}
Output
Sum of first20 natural numbers = 210
Example2-C# program to find sum of N natural Numbers with Method-1 using while loop
class Program
{
static void Main(string[] args)
{
int i, num=20, sum = 0;
i = 1;
while( i <= num)
{
sum = sum + i;
i++;
}
Console.WriteLine("Sum of first" + num +
" natural numbers = " + sum);
}
}
Output
Sum of first20 natural numbers = 210
Example3-C# program to find sum of N natural Numbers with Method-2 using function
class Program
{
static void Main(string[] args)
{
int num=20, sum = 0;
Program P = new Program();
sum = P.findSum(num);
Console.WriteLine("Sum of first" + num +
" natural numbers = " + sum);
}
int findSum(int n)
{
return ((n + 1) * n) / 2;
}
}
Output
Sum of first20 natural numbers = 210
Example4-program to find sum of N natural Numbers with Method-1 using recursive function
class Program
{
static void Main(string[] args)
{
int num=20, sum = 0;
Program P = new Program();
sum = P.findSum(num);
Console.WriteLine("Sum of first" + num +
" natural numbers = " + sum);
}
int findSum(int n)
{
if (n != 0)
return n + findSum(n - 1);
else
return n;
}
}
Output
Sum of first20 natural numbers = 210