Compare in Objective-C

Find this useful? Support us: Star on GitHub 6
Category: String | Language: Objective-C

In Objective-C, we can compare numbers using different comparison operators such as less than, greater than, equal to, less than or equal to, greater than or equal to, etc. Here are some examples of how to compare numbers in Objective-C:

1. Less Than Operator (<):

To check if a number is less than another number, we can use the less than operator (<). For example:

int num1 = 10;
int num2 = 20;

if (num1 < num2) {
NSLog(@"num1 is less than num2");
}

In this example, the if statement will be true because num1 (10) is less than num2 (20). Therefore, the output will be:

num1 is less than num2

2. Greater Than Operator (>):

To check if a number is greater than another number, we can use the greater than operator (>). For example:

int num1 = 30;
int num2 = 20;

if (num1 > num2) {
NSLog(@"num1 is greater than num2");
}

In this example, the if statement will be true because num1 (30) is greater than num2 (20). Therefore, the output will be:

num1 is greater than num2

3. Equal To Operator (==):

To check if two numbers are equal, we can use the equal to operator (==). For example:

int num1 = 10;
int num2 = 10;

if (num1 == num2) {
NSLog(@"num1 is equal to num2");
}

In this example, the if statement will be true because num1 (10) is equal to num2 (10). Therefore, the output will be:

num1 is equal to num2

4. Less Than or Equal To Operator (<=):

To check if a number is less than or equal to another number, we can use the less than or equal to operator (<=). For example:

int num1 = 10;
int num2 = 10;

if (num1 <= num2) {
NSLog(@"num1 is less than or equal to num2");
}

In this example, the if statement will be true because num1 (10) is equal to num2 (10). Therefore, the output will be:

num1 is less than or equal to num2

5. Greater Than or Equal To Operator (>=):

To check if a number is greater than or equal to another number, we can use the greater than or equal to operator (>=). For example:

int num1 = 20;
int num2 = 10;

if (num1 >= num2) {
NSLog(@"num1 is greater than or equal to num2");
}

In this example, the if statement will be true because num1 (20) is greater than num2 (10). Therefore, the output will be:

num1 is greater than or equal to num2

These are just a few examples of how to compare numbers in Objective-C using different comparison operators. The same operators can be used for other numeric data types such as float and double.