0

I have numbers in an array, odd and even, I have to add the odd ones with one another and the even ones wit one another. I am very confused as to how to go about this because of the parameters and conditions given:

In my Adder.h file I have the following:

@interface ConditionalAdder : NSObject

- (instancetype)initWithNumbers:(NSArray *)numbers;

- (int)sumWithCondition:(NSString *)condition;

@end

In my Main.m file I have the following code:

#import "ConditionalAdder.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {

ConditionalAdder *adder1 = [[ConditionalAdder alloc] 
initWithNumbers:@[@1, @2, @3, @4, @5]];
NSLog(@"%i", [adder1 sumWithCondition:@"even"]);
NSLog(@"%i", [adder1 sumWithCondition:@"odd"]);

ConditionalAdder *adder2 = [[ConditionalAdder alloc] 
initWithNumbers:@[@13, @88, @12, @44, @99]];
NSLog(@"%i", [adder2 sumWithCondition:@"even"]);

ConditionalAdder *adder3 = [[ConditionalAdder alloc] 
initWithNumbers:@[]];
NSLog(@"%i", [adder3 sumWithCondition:@"odd"]);
  } 

return 0;
}

I know that this method:

- (int)sumWithCondition:(NSString *)condition;

Should return an integer, but what string am I supposed to pass through the parameter?

1 Answer 1

1

You didn't show your sumWithCondition function. But you can utilize the mod operation which is %. Mod will return 0 if the first number is wholly divisible by the second number.

This should work (assuming your number array is called numbers)

NSArray *numbers;

- (int)sumWithCondition:(NSString *)condition {

    int sum = 0;
    int modCondition = 0;

    if ([condition isEqualToString:@"odd"]) {
        modCondition = 1; //Set Mod condition to odd
    }
    else {
        modCondition = 0; //Set Mod condition to even
    }

    for (int i = 0; i < [numbers count]; i++){ //Iterate over each value in array
        int thisValue = [[numbers objectAtIndex:i] intValue];

        if ((thisValue % 2) == modCondition) { //If value is odd or even depending on condition
            sum += thisValue; //Then add value to sum
        }

    }

    return sum;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Jeshua, sorry never mind, it did! My mistake. Thank you!

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.