C# Example: Using a for loop to iterate over an array, perform an action on each element, and accumulate a result - Biz Tech

C# Example: Using a for loop to iterate over an array, perform an action on each element, and accumulate a result

Listen
 using System;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 1, 3, 5, 7, 9 };

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

        Console.WriteLine("Sum of " + string.Join(", ", numbers) + " is " + sum + ".");

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

        Console.WriteLine("Product of " + string.Join(", ", numbers) + " is " + product + ".");
    }
}

This example uses a for loop to iterate over an array of int values, adds each value to a running total to calculate the sum, and multiplies each value by a running product to calculate the product. The following steps are performed:

  1. Define an array of int values with the values 1, 3, 5, 7, and 9.
  2. Use a for loop to iterate over the array and add each element to a running total sum.
  3. Output the sum to the console using Console.WriteLine().
  4. Use a for loop to iterate over the array and multiply each element by a running product product.
  5. Output the product to the console using Console.WriteLine().

Note that there are many other types of loops you can use, such as while, do-while, and foreach, as well as many other types of operations you can perform within loops, such as sorting, filtering, and searching. This example is just one possible multi-step process for working with loops.