Program to Calculate the Sum of Natural Numbers - (C# Basic Programs)
Calculating the sum of natural numbers is a common programming exercise that helps improve problem-solving skills. In this tutorial, we will discuss a program to calculate the sum of natural numbers using C# programming language.
Syntax
The syntax for calculating the sum of natural numbers in C# is as follows:
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
Here, n
is the number of natural numbers to be added, and sum
is the variable used to store the sum of natural numbers.
Example
using System;
public class Program
{
public static void Main()
{
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
Console.WriteLine("Sum of first {0} natural numbers: {1}", n, sum);
}
}
Output:
Sum of first 10 natural numbers: 55
Explanation
The program first initializes n
to the number of natural numbers to be added, in this case, 10. Then, a for
loop is used to iterate from 1 to n
. Inside the loop, the variable sum
is incremented by the current value of i
. Finally, the program prints the sum of the first n
natural numbers.
Use
Calculating the sum of natural numbers is useful when working with mathematical problems. This can be used as a building block for more complex algorithms.
Summary
In this tutorial, we discussed a program to calculate the sum of natural numbers using C# programming language. We have seen the syntax, example, explanation, and use of calculating the sum of natural numbers. By practicing this programming concept, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges.