CHP - 4 - Flow Control - If
CHP - 4 - Flow Control - If
CHAPTER 4.
Flow Control - If
CENGİZ RİVA
Flow Control
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
#include <stdio.h>
int main ()
{
if(0) printf("condition is true\n");
return 0;
}
if Statement
• There can be more than one expression combined with logical
or arithmetic operators inside the condition.
#include <stdio.h>
void main()
{
int a = 5;
int b = 20;
int c = 15;
if ( a < b && b > c) printf(" 1st AND opr - Condition is true\n");
if ( a > b && b > c ) printf(" 2nd AND opr - Condition is true\n");
if ( a > b || b > c ) printf(" OR opr - Condition is true\n");
if (! (a > b)) printf(" NOT opr - Condition is true\n");
}
if...else Statement
• An if statement can be followed
by an optional else statement,
which executes when the
boolean expression is false.
• If the boolean expression
evaluates to true, then the if
block of code will be executed,
otherwise else block of code
will be executed.
• C programming language
assumes any non-zero and non-
null values as true and if it is
either zero or null then it is
assumed as false value.
if...else Statement
• An if statement can be followed by an optional else
statement, which executes when the boolean expression is
false.
Syntax:
• The syntax of an if...else statement in C programming
language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
if...else Statement
• Example:
#include <stdio.h>
int main ()
{
int a = 100;
/* check the boolean condition */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
if...else Statement
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
Nested if Statements
• Example
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;
if( a == 100 )
{
if( b == 200 )
{
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
Nested if Statements
• Output will be:
if Statements
#include <stdio.h>
int main ()
{
char ch1 = 'a';
char ch2 = 'b';
if( ch1 == 'x')
{
printf("ch1 is a x character\n" );
}
if( ch2 == 'b')
{
printf("ch2 is a b character\n" );
}
printf("Exact character of ch1 : %c\n", ch1 );
printf("Exact character of ch1 : %c\n", ch2 );
return 0;
}
if Statements
• Output will be: