Problem

Write a method to find the sum of all the elements in the integer Array.

Sum of Array

Problem Analysis:-

    • Input: The method will take Integer Array as an input.
    • Process:
      • Declare an int variable sum and initialize with value 0
      • Traversed through the array’s elements using for loop
        • Inside for loop: Add each element value to the sum variable
      • After traversing return the sum value.
    • Output: Sum of all the elements in the Array

Solution:-

SumOfArray Write a method to find the sum of all the elements in the integer Array c# Data Structures and Algorithms   Ohbly.com
The whole code is shared below

Output:-SumOfArray-o Write a method to find the sum of all the elements in the integer Array c# Data Structures and Algorithms   Ohbly.com

Analysis:-  Since all the elements are traversed the Time complexity is O(n)

Code:-

public class SumOfArray
{
    public static int GetSumOfArray(int[] intArray)
    {
        int sum = 0;
        for (int index = 0; index < intArray.Length; index++)
        {
            sum += intArray[index];
        }
        return sum;
    }

    public static void Main()
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        Console.WriteLine($"Sum of all the values in the array: { GetSumOfArray(arr) } ");
    }
}