A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
Welcome to the Even Odd in Objective C page! Here, you'll find the source code for this program as well as a description of how the program works.
#import <Foundation/Foundation.h>
// Function to convert and validate the input string
// Source: ChatGPT
NSInteger convertAndValidateInput(NSString *inputString) {
NSScanner *scanner = [NSScanner scannerWithString:inputString];
NSInteger integerValue = 0;
// Check if the scanner successfully scanned an integer
if ([scanner scanInteger:&integerValue] && [scanner isAtEnd]) {
return integerValue;
} else {
// Raise an exception for invalid input
@throw [NSException exceptionWithName:@"InvalidInputException"
reason:@"Input is not a valid integer"
userInfo:nil];
}
}
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *usage = @"Usage: please input a number";
if (argc < 2) {
printf("%s\n", [usage UTF8String]);
}
else {
NSString* inputStr = [NSString stringWithUTF8String:argv[1]];
@try {
int input = (int)convertAndValidateInput(inputStr);
int remainder = input % 2;
if (remainder == 0) {
printf("Even\n");
}
else {
printf("Odd\n");
}
}
@catch (NSException *) {
printf("%s\n", [usage UTF8String]);
}
}
[pool drain];
return 0;
}
Even Odd in Objective C was written by:
If you see anything you'd like to change or update, please consider contributing.
No 'How to Implement the Solution' section available. Please consider contributing.
No 'How to Run the Solution' section available. Please consider contributing.