if-else
if-else
3
Different forms of if statement
1. Simple if statement
2. if....else statement
3. Nested if......else statement
4. else if ladder
If….
• Simplest form of if for single statement
if(expression)
statement;
• For multiple statements
if(expression)
{
statement 1;
statement 2;
……
statement n;
}
5
If….
• The expression may be any valid
C expression.
6
Old Problem!
• Draw the flowchart of a program that reads two numbers and
print “First” if first number is greater than second.
• The program
Home Task
1. Write a program that will reads a number from terminal
and determine whether this number is ‘odd’ or ‘even’ and
print the message- NUMBER IS EVEN or NUMBER IS ODD
2. Write a program to determine whether a given number is
divisible by 7 and 3 or not.
7
if....
• In C, an expression is true if it evaluates to any
nonzero value.
8
What will happen?
int a=10, b=20;
if(a < b)
printf(“This line will print.”);
Output
9
What will happen?
int a=10, b=20;
if( a > b)
printf(“This line will print.”);
Output
Nothing!
10
What will happen?
int
int a=10,
a=10, b=20;
b=20;
if(
if( 010) )
printf(“This
printf(“This line
line will
will print.”);
print.”);
Output
Output
This line will print.
Nothing!
11
What will happen?
Output
12
Remember!!!
• The result/value produce by the relational and logical
operators is either 0 or 1.
13
ADD THE else!
• We can add else statement to the if.
• The if…else statement is an extension of the simple if
statement.
if(test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
Statement x
14
ADD THE else!
17
Nested if…else
18
Nested if…else
19
Nested if…else
Problem!
A commercial bank has introduced an incentive policy of
giving bonus to all its deposit holders. The policy is as
follows: A bonus of 2 per cent of the balance held on 31st
December is given to every one, inspective of their balance,
and 5 per cent is given to female account holders if their
balance is more than Tk. 50,000.
20
Nested if…else
Problem!
A commercial bank has introduced an incentive policy of
giving bonus to all its deposit holders. The policy is as
follows: A bonus of 2 per cent of the balance held on 31st
December is given to every one, inspective of their balance,
and 5 per cent is given to female account holders if their
balance is more than Tk. 50,000.
21
Conditional Operators
23
The Conditional Operator
•
True or False?
True
24
The Conditional Operator
True or False?
False
25
SELECT ALTERNATIVE WITH THE
switch STATEMENT
• If is good for choosing between two alternatives
Statement sequence
are not blocks, not use
curly braces
Example - switch
if vs switch
• switch can only test for equality, where
the if conditional expression can be of any
type
• switch will work with only int or char
types. We can’t use float or others.
Nested switch!
goto Statement
• Guess what I am going to say!
We will learn
later!