ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Objective-C Array Summation

Objective-C

Goal -- WPM

Ready
Exercise Algorithm Area
1#import <Foundation/Foundation.h>
2
3// Function to calculate the sum of NSNumbers in an array
4NSNumber* sumArrayElements(NSArray<NSNumber *> *numbers) {
5// Handle empty array case
6if (numbers == nil || [numbers count] == 0) {
7return @0; // Return 0 for an empty or nil array
8}
9
10long long totalSum = 0; // Use long long to prevent potential overflow
11
12// Iterate through the array and add each number to the sum
13for (NSNumber *num in numbers) {
14totalSum += [num longLongValue];
15}
16
17return @(totalSum);
18}
19
20int main(int argc, const char * argv[]) {
21@autoreleasepool {
22NSArray<NSNumber *> *myNumbers = @[@1, @2, @3, @4, @5];
23NSNumber *sum = sumArrayElements(myNumbers);
24NSLog(@"Sum of elements: %@", sum);
25
26NSArray<NSNumber *> *emptyArray = @[];
27NSNumber *sumEmpty = sumArrayElements(emptyArray);
28NSLog(@"Sum of empty array: %@", sumEmpty);
29
30NSArray<NSNumber *> *singleElementArray = @[@100];
31NSNumber *sumSingle = sumArrayElements(singleElementArray);
32NSLog(@"Sum of single element array: %@", sumSingle);
33}
34return 0;
35}
Algorithm description viewbox

Objective-C Array Summation

Algorithm description:

This Objective-C code calculates the sum of all `NSNumber` objects within an `NSArray`. It iterates through each element, converts it to a `long long` integer, and accumulates the total sum. This is a fundamental operation for data analysis and aggregation, commonly used when processing numerical datasets or performing calculations on collections of numbers.

Algorithm explanation:

The `sumArrayElements` function computes the sum of numbers in an `NSArray<NSNumber *>`. It first checks for edge cases: if the input array is `nil` or empty, it returns `0`. Otherwise, it initializes a `long long` variable `totalSum` to `0` to accommodate potentially large sums and prevent integer overflow. The code then iterates through each `NSNumber` object in the array using a fast enumeration loop. For each `NSNumber`, it extracts its `long long` value using `longLongValue` and adds it to `totalSum`. Finally, it returns the `totalSum` wrapped in an `NSNumber`. The time complexity is O(n), where n is the number of elements in the array, as each element is processed exactly once. The space complexity is O(1) because only a few variables are used, regardless of the input array size.

Pseudocode:

function sumArrayElements(numbers):
  if numbers is nil or empty:
    return 0

  totalSum = 0

  for each number in numbers:
    totalSum = totalSum + number

  return totalSum