
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
Editorial
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. |
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.