Calculating the sum of natural numbers is a fundamental problem in programming. It involves adding up numbers from 1 to a given positive integer. In this article, we will walk through the process of solving this problem using C# and provide a detailed step-by-step guide.
Problem Statement: Write a C# program to calculate the sum of natural numbers up to a given positive integer n.
Example:
Input: n = 5 Output: 15 Explanation: The sum of Natural Number from 1 to 5 is 15.
Steps to Find Sum of Natural Numbers.
C# Code to Find Sum of Natural Numbers Using Loop.
// C# code to find the sum of natural numbers using System; namespace SumOfNaturalNumbers { class Program { static void Main(string[] args) { Console.Write("Enter a positive integer: "); int n = Convert.ToInt32(Console.ReadLine()); int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } Console.WriteLine($"Sum of natural numbers from 1 to {n} is {sum}"); } } }
Enter a positive integer: 6
Sum of natural numbers from 1 to 6 is 21
C# Code to Find Sum Natural Number Using Formula.
// C# code to find the sum of natural numbers using System; namespace SumOfNaturalNumbers { class Program { static void Main(string[] args) { Console.Write("Enter a positive integer: "); int n = Convert.ToInt32(Console.ReadLine()); int sum = 0; //formula to calculate sum of natural numbers sum = n * (n + 1) / 2; Console.WriteLine($"Sum of natural numbers from 1 to {n} is {sum}"); } } }
Enter a positive integer: 5
Sum of natural numbers from 1 to 5 is 15
