Search code examples
objective-cnsarray

How to multiply respective objects of NSArray and get the sum?


I have one array with data A=[a,b,c] and another with data B=[d,e,f]. I need to perform this type of operation a.d+ b.e+c.f (Note=Here (.) denotes multplication)and get the result. How can i do that using Objective-C? Thanks in advance.


Solution

  •     NSNumber *myNum1 = [NSNumber numberWithInt:1];
        NSNumber *myNum2 = [NSNumber numberWithInt:2];
        NSNumber *myNum3 = [NSNumber numberWithInt:3];
    
        NSArray *a = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
        NSArray *b = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
        int sum=0;
        for (int i=0; i<[a count]; i++) {
            NSLog(@"%@", (NSNumber*)[a objectAtIndex:i]);
            sum =sum +[(NSNumber*)[a objectAtIndex:i] intValue]*[(NSNumber*)[b objectAtIndex:i] intValue];
        }
        NSLog(@"Sum is %d", sum);
    

    Hope this helps