Objective C Tutorial - Objective C if Statement






An if statement contains a boolean expression followed by one or more statements.

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

We nest one if or if else statement inside another if or else if statement(s).

Syntax

The syntax of an if statement in Objective-C programming language is:

if(boolean_expression)
{
   /* statement(s)*/
}

If the boolean expression is true, then the statement(s) will be executed.

If boolean expression is false, then the first statement after the if statement closing curly brace will be executed.

The syntax of an if...else statement:

if(boolean_expression)
{
   /* statement(s) */
}
else
{
  /* statement(s) */
}

The syntax of an if...else if...else statement is:

if(boolean_expression 1)
{
   ...
}
else if( boolean_expression 2)
{
   ...
}
else if( boolean_expression 3)
{
   ...
}
else 
{
   ...
}




if statement Example

#import <Foundation/Foundation.h>
 
int main ()
{
   int a = 10;
 
   if( a < 20 )
   {
       NSLog(@"a is less than 20\n" );
   }
   NSLog(@"value of a is : %d\n", a);
 
   return 0;
}




if else Example

#import <Foundation/Foundation.h>
 
int main ()
{
   int a = 100;
 
   if( a < 20 )
   {
       NSLog(@"a is less than 20\n" );
   }
   else
   {
       NSLog(@"a is not less than 20\n" );
   }
   NSLog(@"value of a is : %d\n", a);
 
   return 0;
}

if else if statement Example

#import <Foundation/Foundation.h>
 
int main ()
{
   int a = 100;
 
   if( a == 10 )
   {
       NSLog(@"Value of a is 10\n" );
   }
   else if( a == 20 )
   {
       NSLog(@"Value of a is 20\n" );
   }
   else if( a == 30 )
   {
       NSLog(@"Value of a is 30\n" );
   }
   else
   {
       NSLog(@"None of the values is matching\n" );
   }
   NSLog(@"Exact value of a is: %d\n", a );
 
   return 0;
}

The code above generates the following result.

Nested if statement Example

#import <Foundation/Foundation.h>
 
int main ()
{
   int a = 100;
   int b = 200;
 
   if( a == 100 )
   {
       if( b == 200 )
       {
          NSLog(@"Value of a is 100 and b is 200\n" );
       }
   }
   NSLog(@"Exact value of a is : %d\n", a );
   NSLog(@"Exact value of b is : %d\n", b );
 
   return 0;
}

The code above generates the following result.

if statement and BOOL type variable

#import <Foundation/Foundation.h>
 
int main ()
{
  BOOL Flag = YES;
    if (Flag) NSLog (@"It works!");
 
   return 0;
}

The code above generates the following result.