1

I have the data into the mutable array and the value of array is,

     { "20", "40", "50","60", "70"}.

I have stored the string values into the array.

Now i want to total value of the array. Result is : 240

Thanks!

5 Answers 5

5
NSInteger value = 0;
for (String *digit in myArray) {
    value += [digit intValue];
}
Sign up to request clarification or add additional context in comments.

Comments

2
int total=0;
for(NSString *currentString in myArray){
     total +=[currentString intValue]; 
}
NSLog(@"Sum:%d",total);

Comments

0

This adds all values:

__block NSInteger sum = 0;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    sum += [obj intValue];
}];

Comments

0

You can do as follows:

int totalSum = 0;
NSmutableArray *arrayData = [[NSmutableArray alloc] init];
[arrayData addObject:@"20"];
[arrayData addObject:@"40"];
[arrayData addObject:@"50"];
[arrayData addObject:@"60"];
[arrayData addObject:@"70"];

for(int i=0; i<[arrayData count];i++)
{
     totalSum = totalSum + [[arrayData objectAtIndex:i] intValue];
}

NSLog(@"Total:%d",totalSum);

Please let me know if you have any question.

2 Comments

You forget alloc and init arrayData.
Now I changed my answer and also allocated the arrayData.
0

How about the most elegant solution using key-value Collection aggregators:

NSNumber *sum = [myArray valueForKeyPath:@"@sum.self"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.