Tutorialspoint
Problem
Solution
Submissions

Sum of Elements in a Dynamically Allocated Array

Certification: Basic Level Accuracy: 87.5% Submissions: 16 Points: 5

Write a C++ program that finds the sum of elements in a dynamically allocated array.

Example 1
  • Input: arr = [1, 2, 3, 4, 5], size = 5
  • Output: 15
  • Explanation:
    • Step 1: Dynamically allocate memory for an array of size 5.
    • Step 2: Initialize the array with the given values [1, 2, 3, 4, 5].
    • Step 3: Initialize a sum variable to 0.
    • Step 4: Iterate through the array using pointers and add each element to the sum.
    • Step 5: Return the sum value (1 + 2 + 3 + 4 + 5 = 15).
Example 2
  • Input: arr = [10, 20, 30], size = 3
  • Output: 60
  • Explanation:
    • Step 1: Dynamically allocate memory for an array of size 3.
    • Step 2: Initialize the array with the given values [10, 20, 30].
    • Step 3: Initialize a sum variable to 0.
    • Step 4: Iterate through the array using pointers and add each element to the sum.
    • Step 5: Return the sum value (10 + 20 + 30 = 60).
Constraints
  • 1 ≤ size ≤ 10^6
  • Use dynamic memory allocation
  • Time Complexity: O(n) where n is the size of the array
  • Space Complexity: O(n) where n is the size of the array
ArraysPointers and ReferencesCognizantWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Allocate memory for the array dynamically.
  • Traverse the array and calculate the sum of its elements.
  • Ensure that the memory is properly deallocated after use.

Steps to solve by this approach:

 Step 1: Define a function sum_array that takes an integer pointer and size as parameters.

 Step 2: Initialize a sum variable to zero.
 Step 3: Iterate through the array using a for loop from 0 to size-1.
 Step 4: Add each array element to the sum.
 Step 5: Return the final sum value.
 Step 6: In main, dynamically allocate an array with values.
 Step 7: Call sum_array with this array and its size, then print the result.
 Step 8: Free the dynamically allocated memory using delete[].

Submitted Code :