Q. Write an algorithm and program to find sum of first n natural numbers?
Sum Of First N Natural Numbers : This section focuses on sum of first n natural numbers algorithm and program. This program should be practiced to improve the coding skills required for various interviews (campus interviews, walk-in interviews), coding rounds etc.
Natural Numbers : Natural numbers include all whole numbers excluding 0.
Given a number n and our task to print the sum of first n natural numbers.
For Example :-
Input : n = 3
Output : 6
Explanation : As we can see that input number is 3. Now, we need to add the natural number till 3 : 1 + 2 + 3 . So, output for the following code is sum of 1 + 2 + 3 = 6.
Now let us understand what logic we need to use in this -
1. Firstly, we need to Initialize an integer sum = 0.
2. Loop will run throughout the program.The loop will start from i = 1 to n.
3. Add sum = sum + x.
Algorithm To Find The Sum Of First N Natural Numbers
\\Algorithm To Find The Sum Of First N Natural Numbers START Step 1 : Initialize : sum = 0 Step 2 : Loop Starts from x = 1 to n : sum = sum + x Step 3 : Print sum Stop
Program To Find The Sum Of First N Natural Numbers
//C Program To Find The Sum Of First N Natural Numbers #include <stdio.h> int main() { int n = 5, add = 0; for (int i=1; i<=n; i++) { add = add + i; } printf("%d",add); return 0; }
//C++ Program To Find The Sum Of First N Natural Numbers #include <iostream> using namespace std; int main() { int n = 5, add = 0; for (int i=1; i<=n; i++) { add = add + i; } cout<<add; return 0; }
//Java Program To Find The Sum Of First N Natural Numbers public class LFC { public static void main(String[] args) { int n = 5, add = 0; for (int i=1; i<=n; i++) { add = add + i; } System.out.println(add); } }
#Python Program To Find The Sum Of First N Natural Numbers add = 0 n = 5 i = 1 while i <=n : add = add + i i = i + 1 print(add)
//C# Program To Find The Sum Of First N Natural Numbers using System; class LFC { static void Main() { int n = 5, add = 0; for (int i=1; i<=n; i++) { add = add + i; } Console.WriteLine(add); } }
<?php //PHP Program To Find The Sum Of First N Natural Numbers $n = 5; $add = 0; for ($i = 1; $i <= $n; $i++) $add = $add + $i; echo $add;
//C Program To Find The Sum Of First N Natural Numbers #include <stdio.h> int main() { int n = 5, add = 0; for (int i=1; i<=n; i++) { add = add + i; } printf("%d",add); return 0; }
Output
Sum Of First N Natural Numbers : 15
Recommended Programs
Program for left array rotationProgram to find square root of a number