OneBite.Dev - Coding blog in a bite size

Find The Product Of All Elements In An Array In C#

Code snippet for how to Find The Product Of All Elements In An Array In C# with sample and detail explanation

Finding the product of all elements in an array is a common task in programming. This article provides a simple and easy-to-understand demonstration of achieving this using C# programming language.

Code snippet: Product of All Elements in an Array

using System; 

public class Program 
{ 
    public static void Main() 
    { 
        int[] Array = {2, 3, 4, 5}; 
        int product = 1; 

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

        Console.WriteLine("Product of all elements in the array is: " + product); 
    } 
}

Code Explanation for Product of All Elements in an Array

Let’s break the code down:

  1. Import the System namespace using the using System; command, which contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
  2. The public class Program declares a public class named ‘Program’. This is basically saying “Here’s a blueprint for creating a ‘Program’ object.” It is C# customary to name the class that contains the Main method as ‘Program’.
  3. Inside the Program class, we declare the main method where the program start execution public static void Main(). It is the entry point from the operating system into our program and is by default called by .NET runtime.
  4. We initialize an integer array int[] Array = {2, 3, 4, 5};, which has four elements 2, 3, 4, and 5.
  5. We declare a variable called ‘product’ and initialize it to 1. We will use this variable to continue multiplying each upcoming element of the array.
  6. A for-loop is initiated to iterate and access each element of the array. The variable ‘i’ is used as a counter, and ‘Array.Length’ is a property in C# that gets the total number of elements in the array.
  7. In each iteration, we multiply the current ‘Array[i]’ element with the existing ‘product’ and store back in the product variable. This continues for all the elements of the array.
  8. The product of all the elements in the array is then printed using Console.WriteLine().

The above code will output 120 because 2 * 3 * 4 * 5 equals 120.

c-sharp