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.
Below are the steps that you need to follow to solve this problem:
Step 1: Take an integer n as input, which represents the upper limit of the natural numbers.
Step 2: Declare a variable sum and set it to 0. This variable will be used to store the sum of the natural numbers.
Step 3: Use a for loop to iterate through numbers from 1 to n.
Step 4: In each iteration of the loop, add the current number to the sum variable.
Step 5: After the loop completes, output the value of the sum variable as the sum of natural numbers from 1 to n.
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.
We can also find the sum of n natural numbers using the formula sum = n * (n + 1) / 2.
// 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}"); } } }
Output:
Enter a positive integer: 5
Sum of natural numbers from 1 to 5 is 15
Similar articles:
No comments:
Post a Comment