Sum of numbers using for loop in C#

Sum of numbers using for loop in C#


  Calculating the Sum of Numbers Using a For Loop in C Sharp 

Introduction

In programming, calculating the sum of numbers is a fundamental task that can be accomplished in various ways. One of the simplest and most efficient methods in C# is using a for loop. This article will guide you through this process with an example.

Using a For Loop for Summation

A for loop in C# allows you to iterate over a series of numbers, making it perfect for summing a sequence of values.

Example: Summing Numbers in an Array

Let's say you have an array of numbers and you want to calculate their sum.

 

int[] numbers = { 1, 2, 3, 4, 5 };
int sum = 0;

for (int i = 0; i < numbers.Length; i++)
{
    sum += numbers[i];
}

Console.WriteLine("The sum is: " + sum);

Explanation:

  • We declare an array numbers containing the numbers to be summed.
  • We initialize a variable sum to 0, which will hold the total sum.
  • We use a for loop to iterate through each element in the array.
    • i is the loop variable, starting at 0.
    • i < numbers.Length ensures the loop runs for each element in the array.
    • i++ increments i after each loop iteration.
  • Inside the loop, we add each element (numbers[i]) to sum.
  • After the loop completes, we print the total sum.

Why Use a For Loop?

  • Simplicity: A for loop provides a straightforward way to iterate through items.
  • Control: You have full control over the iteration process.
  • Versatility: It can be used with arrays, lists, or any collection of items.

Conclusion

The for loop is a versatile and powerful tool in C# for iterating over sequences and performing calculations like summing numbers. It's an essential technique for beginners to learn and a fundamental part of many programming tasks.

Further Practice

Try modifying the example to calculate the sum of only even numbers or apply other conditions to practice and understand the flexibility of for loops in C#.

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