The programmer must define one or more criteria to be evaluated or tested by the program. They should also be mindful about a statement(s) to be performed if the condition is found to be true/false, and optionally, further statements to be run if the condition is found to be true/false.
Any non-zero and non-null values are presumed to be true in the Objective-C programming language, whereas zero and null values are believed to be false. Some assertion operators are used to calculate them. These assertions can be if, if-else, nested if, switch, or ternary operator.
if-else
statementThe if-else
or nested if-else
blocks in Objective-C are used for decision-making. Let's elaborate on a real-world example:
if (condition) {/* code block */}else {/* ----other conditions---- */}
In the code below, we check whether the value of x
variable is greater than 20
or not. Then we print a message on the console accordingly.
#import <Foundation/Foundation.h>int main() {NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];/* define an integer x with 50 value */int x = 50;/* used if to check a condition*/if( x > 20 ) {NSLog(@"x is greater than 20\n" );} else {NSLog(@"x is not greater than 20\n" );}[pool drain];return 0;}
x
with a default value 50
.if-else
block to check whether the value of x is greater than 20
or not. If the value of x is greater than 20, then we print "x is greater than 20"
.x
is less than 20
, it prints "x is not greater than 20"
in the else block.We can also use the ternary operator as a comparison operator in objective-C to compare values and make decisions.
Condition ? condition: text
In the code below, we implement the ternary operator in Objective-C with a real example:
#import <Foundation/Foundation.h>int main() {NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];int x = 50;x > 20 ? NSLog(@"x is greater than 20\n" ) : NSLog(@"x is less than 20\n");[pool drain];return 0;}
50
as the default value. x
is greater than 20
or not.Switch
statementThe switch
statement is used to make decisions just like the if-else
or ternary operator.
Switch(variable) {case :// condition blockbreak;// condition blockdefault:// default code to execute block}
In the code below, we have switch
statements to print the grade of a student.
#import <Foundation/Foundation.h>int main() {NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];/* define an character with default F */char grade = 'F';/* Using switch statement */switch (grade) {case 'A':NSLog(@"Your grade is A");break;case 'F':NSLog(@"Your grade is F, Try again");break;default:NSLog(@"Incorrect information");}[pool drain];return 0;}
F
.F
is compared with A
. It results in a false, and the next case statement is executed.F
is equal to case F
. Hence, it prints a statement, "Your grade is F, Try again"
.