skypirate
skypirate

Reputation: 673

Sum is returning some vague values. All I want to do is get Sum of Elements in my Mutable Array

& yes I did google "How to get sum of array elements" but I want to know what's going on wrong here? If I use break points and see after execution of this line "sum = sum + (int) A[i];" sum has some vague values.

#import <Foundation/Foundation.h>

@interface MyClass : NSObject
@end
@implementation MyClass
@end

int solution(NSMutableArray *A) 
{
  int sum = 0;
  for (int i = 0; i <A.count; i ++)
  {
    NSLog(@"A.count: %ld", A.count);
    sum = sum + (int) A[i];   //A[i] has to return a value right?**strong text** 
  }
   NSLog(@"The final sum is: %d", sum);
   return sum;
}

int main(int argc, const char * argv[]) 
{
@autoreleasepool 
{
    NSMutableArray *A = [NSMutableArray arrayWithObjects: @"3",@"1",@"2",@"4",@"3", nil];
    solution(A);        
}
return 1;
}

Upvotes: 0

Views: 43

Answers (2)

johnpatrickmorgan
johnpatrickmorgan

Reputation: 2372

The elements within your array are NSString objects. You should use NSNumber objects:

NSMutableArray *A = [@[@3,@1,@2,@4,@3] mutableCopy];

Also, you can't just cast them as ints. To get an int from an NSNumber you would need to call call [A[i] intValue]. Otherwise you will be summing the pointer values.

 sum = sum + [A[i] intValue];

Upvotes: 3

Ben Avery
Ben Avery

Reputation: 1724

You are adding the values of the string instead of the integer values. Simply replace

sum = sum + (int) A[i];

with the following

sum = sum +  [A[i] integerValue];

Upvotes: 1

Related Questions