How to calculate sum in c#

How to calculate sum in c#



 Calculating Sums in C#: A Guide for Beginners

Introduction

One of the fundamental tasks in programming is calculating sums. In C#, there are several ways to achieve this, suitable for different scenarios. This article will walk you through these methods with simple explanations and examples.

Method 1: Using a Loop

The most basic method to calculate the sum of numbers is by using a loop.

int[] numbers = { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (int number in numbers)
{
    sum += number;
}
Console.WriteLine("Sum: " + sum);

Explanation:

  • We have an array numbers.
  • We initialize a variable sum to 0.
  • We use a foreach loop to iterate through each element of the array.
  • In each iteration, we add the current number to sum.

Method 2: Using LINQ

LINQ (Language Integrated Query) provides a more concise way to sum numbers.

 

int[] numbers = { 1, 2, 3, 4, 5 };
int sum = numbers.Sum();
Console.WriteLine("Sum: " + sum);

Explanation:

  • We use the same array numbers.
  • The Sum() method provided by LINQ is called on the array.
  • This method automatically calculates the sum of elements.

Method 3: Using the Aggregate Method

Another LINQ method, Aggregate, can also be used for more complex summations.

int[] numbers = { 1, 2, 3, 4, 5 };
int sum = numbers.Aggregate((acc, n) => acc + n);
Console.WriteLine("Sum: " + sum);

Explanation:

  • The Aggregate method takes a lambda function.
  • acc is the accumulator that holds the sum so far, and n is the current number.
  • The lambda function defines how the numbers are aggregated.

Conclusion

Calculating sums in C# is straightforward. Beginners can start with loops for a more hands-on approach. As you become more comfortable, LINQ methods like Sum and Aggregate offer more powerful and concise ways to perform such calculations.

 

 

 


Leave a reply Your email address will not be published. Required fields are marked*

Popular Posts

Simplifying Resilience Strategies with Polly in .NET

5 months ago
Simplifying Resilience Strategies with Polly in .NET

c# sortedset performance

4 months ago
c# sortedset performance

What is a Delegate in C#?

5 months ago
What is a Delegate in C#?

How to use hashtable in c# with example

4 months ago
How to use hashtable in c# with example

Tags