0% found this document useful (0 votes)
198 views

If-Else Statements: Branching

Conditional statements let programs choose which statements to execute based on certain conditions being true or false. The document discusses the if, if-else, and if-else if-else ladder conditional statements in C and provides examples of using each to make decisions based on inputs. Logical operators are used to check conditions. Block statements allow grouping multiple statements to execute based on a condition. Examples are given to demonstrate using conditional statements to check inputs and determine outputs like grades, leap years, and largest numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views

If-Else Statements: Branching

Conditional statements let programs choose which statements to execute based on certain conditions being true or false. The document discusses the if, if-else, and if-else if-else ladder conditional statements in C and provides examples of using each to make decisions based on inputs. Logical operators are used to check conditions. Block statements allow grouping multiple statements to execute based on a condition. Examples are given to demonstrate using conditional statements to check inputs and determine outputs like grades, leap years, and largest numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

BRANCHING

if-else statements

Conditional Statements
• A conditional statement lets us choose which
statement will be executed next

• Therefore they are sometimes called selection


statements

• Conditional statements give us the power to


make basic decisions

• The C conditional statements are the:


 if statement
 if-else statement
 if-else if-else if-else ladder
 switch statement
 Conditional operator (?:)

1
The if Statement
• The if statement has the following syntax:

The condition must be a


boolean expression. It must
if is a C evaluate to either true or false.
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.

The if Statement (Example)


• Selection structure:
– Used to choose among alternative courses of action
– Pseudocode: If student’s mark is greater than or equal to 60
Print “Passed”
• Pseudocode statement in C:
#include <stdio.h>
main()
{
float marks;
printf(“Enter your marks: “);
scanf(“%f”, &marks);
if ( marks >= 60 )
printf( "Passed\n" );
}

2
Logic of an if statement

condition
evaluated

true
false

statement

Relational Operators
• A condition often uses one of C's equality
operators or relational operators

== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

• Note the difference between the equality operator


(==) and the assignment operator (=)

3
The if-else Statement
• An else clause can be added to an if statement to
make an if-else statement

if ( condition )
statement1;
else
statement2;

• If the condition is true, statement1 is executed;


if the condition is false, statement2 is executed

• One or the other will be executed, but not both

if statement analogy (Y-intersection)

4
Logic of an if-else statement

condition
evaluated

true false

statement1 statement2

The if-else Statement (Example)


• Selection structure:
– Pseudocode: If student’s mark is greater than or equal to 60
Print “Passed”
Otherwise
Print “Failed”
• Pseudocode statement in C:
#include <stdio.h>
main()
{
float marks;
printf(“Enter your marks: “);
scanf(“%f”, &marks);
if ( marks >= 60 )
printf( "Passed\n" );
else
printf(“Failed\n”);
}

5
Logic of previous example

printf(“Enter your marks: “);


scanf(“%f”, &marks);

marks >= 60

true false

printf (“Passed”); printf (“Failed”);

Write down a program that will take a


number n as input and will determine
whether it is an odd or even number.

#include <stdio.h>
main()
{
int n,r;
printf(“Enter a number:“);
scanf(“%d”, &n);
r = n%2;
if ( r == 0 )
printf( “EVEN\n" );
else
printf(“ODD\n”);
}

6
Block Statements
• Several statements can be grouped together into a
block statement delimited by braces

• A block statement can be used wherever a


statement is called for in the C syntax rules

if (marks >= 60)


printf ("Congratulations!!\n");
else
printf("Sorry…“);

Block Statements
• Several statements can be grouped together into a
block statement delimited by braces

• A block statement can be used wherever a


statement is called for in the C syntax rules

if (marks >= 60){


printf ("Congratulations!!\n");
printf("You made it");
}
else{
printf("Sorry…“);
printf(“Work Hard“);
}

7
Examples
• Write down a program that will take two integers
as input and will print the maximum of two.

• Write down a program that will take three integers


as input and will print the maximum of three.

• Write down a program that will take three integers


as input and will print the second largest.

Largest and Second largest


a b c
4 21 36

s=4 m = 21

Third element
c

c>m s < c <= m c <= s

s=m s=c ignore


m=c

8
Examples

Write a C program that calculates weekly wages


for hourly employees. Number of hours worked
in a week will be input to your program.
 Regular hours 0-40 are paid at the rate of $10/hours.
 Overtime (> 40 hours per week) is paid at the rate of
150% of regular hourly rate.

The if-else if-else if –else ladder


• If-else if- else if –else can be used to select from
multiple choices:
if ( condition1 )
statement1;
else if ( condition2 )
statement2;


else if ( conditionk )
statementk;
else
statement;
• If the condition1 is true, statement1 is
executed; if condition2 is true, statement2 is
executed; and so on

• If more than one condition is satisfied the first one


from the top will get the priority.

9
Logic of an if-else if-else statement

false
condition 1
evaluated

false
true condition 2
evaluated

statement1
true condition k false
evaluated
statement2
statement
true

statement3

Example 1
The following chart will be used for a quick grade
conversion in C programming language course:

90-100 A m >= 90 and m <= 100


80-89 B m >= 80 and m < 90
70-79 C m >= 70 and m < 80
60-69 D m >= 60 and m < 70
0-59 F m >= 0 and m < 60

Write down a program that will take a student’s mark


as input and will convert it to the corresponding
letter grade.

10
Example 2

• Write down a program that will determine


whether a year given as input is leap year or not.

Leap year explained

It takes about
Precisely 365365.2425
it takes days to complete
days! one rotation

11
Leap year explained
Adjustments are needed!

Leap year explained


• Leap year condition

1, 2, 3, 4, 5, 6, 7, 8, …..,96, 100, 104, ….200, …. ,300, …,400,


…500, …, 600, …, 700, …., 800, …, 900, … ,1000……

• Blue numbers leap year Divisible by 400


• Red numbers NOT leap year Divisible by 100
(but not by 400)
• Green numbers leap year Divisible by 4
(but not by 100 or 400)
• Black numbers NOT leap year Not divisible by 4

12
• #include <stdio.h>
main()
{
int year;
printf(“Enter year: “);
scanf(“%d”, &year);
if ( year%400 == 0 )
printf( “Leap Year\n" );
else if ( year%100 == 0 )
printf( “ Not a Leap Year\n" );
else if ( year%4 == 0 )
printf( “Leap Year\n" );
else
printf( “ Not a Leap Year\n" );

Write down a program that will take an integer as


input and will print YES if it is divisible by either 2
or 5 and will print NO otherwise.

Write down a program that will take an integer as


input and will print YES if it is divisible by 2 but not
by 5 and will print NO otherwise.

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20

13
Combining multiple conditions:
Logical Operators
• C defines the following logical operators:
! Logical NOT
&& Logical AND
|| Logical OR

• Logical NOT is a unary operator (it operates on


one operand)

• Logical AND and logical OR are binary operators


(each operates on two operands)

Logical NOT
• The logical NOT operation is also called logical
negation or logical complement
• If some condition a is true, then !a is false; if a is
false, then !a is true

• Logical expressions can be shown using a truth


table

a !a
true false
false true

14
Example
• Selection structure:
– Used to choose among alternative courses of action
– Pseudocode: If student’s mark is greater than or equal to 40
Print “Passed”
• Pseudocode statement in C:
#include <stdio.h>
main()
{
float marks;
printf(“Enter your marks: “);
scanf(“%f”, &marks);
if ( marks >= 60 )
printf( "Passed\n" );
}

Example
• Selection structure:
– Used to choose among alternative courses of action
– Pseudocode: If student’s mark is greater than or equal to 40
Print “Passed”
• Pseudocode statement in C:
#include <stdio.h>
main()
{
float marks;
printf(“Enter your marks: “);
scanf(“%f”, &marks);
if (!( marks < 60 ))
printf( "Passed\n" );
}

15
Logical AND and Logical OR
• The logical AND expression

a && b

is true if both a and b are true, and false otherwise

• The logical OR expression

a || b

is true if a or b or both are true, and false


otherwise

Logical Operators
• A truth table shows all possible true-false
combinations of the terms

• Since && and || each have two operands, there


are four possible combinations of conditions a
and b

a b a && b a || b

true true true true


true false false true
false true false true
false false false false

16
Example 1
The following chart will be used for a quick grade
conversion in C programming language course:

90-100 A m >= 90 and m <= 100


80-89 B m >= 80 and m < 90
70-79 C m >= 70 and m < 80
60-69 D m >= 60 and m < 70
0-59 F m >= 0 and m < 60

Write down a program that will take a student’s mark


as input and will convert it to the corresponding
letter grade.

Example
• Write down a program that will take an English
letter as input and will determine whether it is a small
letter or capital letter.

• Write down a program that will take an English


letter as input and will determine whether it is vowel
or consonant.

17
ASCII chart

Example:
• Write a C program that calculates the discount of
Agora shop. The discount rate depends on the
purchase amount and provided below:

Purchase amount Discount rate


==================== ===========
5,000 TK or less 5% a >= 0 and a <= 5000
For next 5000 TK 10% a > 5000 and a <= 10000
For rest amount 20% a > 10000

18
Example
A triangle is valid if sum of its two sides is greater
than the third side. Now, write a C program to check
the validity of a triangle if the three sides are given.

Leap year explained


• Leap year condition

1, 2, 3, 4, 5, 6, 7, 8, …..,96, 100, 104, ….200, …. ,300, …,400,


…500, …, 600, …, 700, …., 800, …, 900, … ,1000……

• Blue numbers leap year Divisible by 400


• Red numbers NOT leap year Divisible by 100
(but not by 400)
• Green numbers leap year Divisible by 4
(but not by 100 or 400)
• Black numbers NOT leap year Not divisible by 4

19
#include <stdio.h>
main()
{
int year;
printf(“Enter year: “);
scanf(“%d”, &year);
if ( BLUE OR GREEN )
printf( “Leap Year\n" );
else
printf( “Not a Leap Year\n" );

#include <stdio.h>
main(){
int year;
printf(“Enter year: “);
scanf(“%d”, &year);
if ((year%400 == 0)||((year%4 == 0) && (year%100 != 0))
printf( “Leap Year\n" );
else
printf( “Not a Leap Year\n" );

20
Boolean Expressions in C
• C does not have a boolean data type.

• Therefore, C compares the values of variables and


expressions against 0 (zero) to determine if they
are true or false.

• If the value is 0 then the result is implicitly


assumed to be false.

• If the value is different from 0 then the result is


implicitly assumed to be true.

• C++ and Java have boolean data types.

Values on condition
• Zero (0)  False
• Anything nonzero  TRUE

if (40)
printf(" Hi \n" );
else
printf(“ Bye \n" );
Output: Hi
if (-40)
printf(" Hi \n" );
else
printf(“ Bye \n" );
Output: Hi

21
Relational Operators
• Zero (0)  False
• Anything nonzero  TRUE

if (0)
printf(" Hi \n" );
else
printf(“ Bye \n" );
Output: Bye
a = 40;
if (a)
printf(" Hi \n" );
else
printf(“ Bye \n" );
Output: Hi

Relational Operators
• Zero (0)  False
• Anything nonzero  TRUE
a = 0;
if (a)
printf(" Hi \n" );
else
printf(“ Bye \n" );
Output: Bye
a = 30;
if (a = 0)
printf(" Hi \n" );
else
printf(“ Bye \n" );
Output: Bye

22
Relational Operators
• FALSE  Zero (0)
• TRUE  One (1)

a = 5;
printf("%d ", a > 5 );
Output: 0
a = 5;
printf("%d ", a == 5 );
Output: 1

Short-Circuited Operators
• The processing of logical AND and logical OR is
“short-circuited”

• If the left operand is sufficient to determine the


result, the right operand is not evaluated

if (count != 0 && total/count > MAX)


printf ("Testing…");

• This type of processing must be used carefully

23
The Conditional Operator
• C has a conditional operator that uses a boolean
condition to determine which of two expressions
is evaluated

• Its syntax is:

condition ? expression1 : expression2

• If the condition is true, expression1 is


evaluated; if it is false, expression2 is evaluated

• The value of the entire conditional operator is the


value of the selected expression

24
The Conditional Operator
• The conditional operator is similar to an if-else
statement, except that it is an expression that
returns a value

• For example:
larger = ((num1 > num2) ? num1 : num2);

• If num1 is greater than num2, then num1 is assigned


to larger; otherwise, num2 is assigned to larger

• The conditional operator is ternary because it


requires three operands

Example:
• Write a C program that will find the absolute value
of a number. You can only use the ternary
operator.

• Write a C program that will find the minimum,


maximum and second largest of three integers
given as input. You can only use the ternary
operator.

25
The switch Statement
• The switch statement provides another way to
decide which statement to execute next

• The switch statement evaluates an expression,


then attempts to match the result to one of several
possible cases

• Each case contains a value and a list of


statements

• The flow of control transfers to statement


associated with the first case value that matches

The switch Statement


• Often a break statement is used as the last
statement in each case's statement list

• A break statement causes control to transfer to the


end of the switch statement

• If a break statement is not used, the flow of control


will continue into the next case

• Sometimes this may be appropriate, but often we


want to execute only the statements associated
with one case

26
The switch Statement
• The general syntax of a switch statement is:

switch switch ( expression )


and {
case case value1 :
are statement-list1;
reserved case value2 :
words statement-list2;
case value3 :
statement-list3; If expression
case ... matches value2,
control jumps
} to here

The switch Statement


• A switch statement can have an optional default
case

• The default case has no associated value and


simply uses the reserved word default

• If the default case is present, control will transfer


to it if no other case value matches

• If there is no default case, and no other value


matches, control falls through to the statement
after the switch

27
The switch Statement example
• Write down a program using switch structure that
will take an integer as input and will determine
whether the number is odd or even.

switch (n%2){
case 0:
printf(“It is Even”);
break;
case 1:
printf(“It is ODD”);
break;
}

The switch Statement example


• Write down a program using switch structure that
will take an integer as input and will determine
whether the number is multiple of 3 or not.

switch (n%3){
case 0:
printf(“It is Multiple of 3”);
break;
case 1:
printf(“No it’s not”);
break;
case 2: printf(“No it’s not”);
break;
}

28
The switch Statement example
• Write down a program using switch structure that
will take an integer as input and will determine
whether the number is multiple of 3 or not.

switch (n%3)
{
case 0:
printf(“It is Multiple of 3”);
break;
default:
printf(“No it’s not”);
break;
}

This is deliberate….
scanf(“%c”,&ch);
switch (ch)
{
case ‘a’: printf(“It is Vowel”);
break;
case ‘e’: printf(“It is Vowel”);
break;
……

case ‘u’: printf(“It is Vowel”);


break;
default: printf(“It is consonant”);
}

29
This is deliberate….
scanf(“%c”,&ch);
switch (ch)
{
case ‘a’: printf(“It is Vowel”);
break;
case ‘e’: printf(“It is Vowel”);
break;
……

case ‘u’: printf(“It is Vowel”);


break;
default: printf(“It is consonant”);
}

This is deliberate….
scanf(“%c”,&ch);
switch (ch)
{
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’: printf(“It is Vowel”);
break;
default: printf(“It is consonant”);
}

30
Limitations of the switch Statement
• The expression of a switch statement must result
in an integral type, meaning an integer (byte,
short, int,) or a char

• It cannot be a floating point value (float or


double)

• The implicit test condition in a switch statement


is equality

• You cannot perform relational checks with a


switch statement

Can we work around with switches


limitations? One example…..
The following chart will be used for a quick grade
conversion in C programming language course:

90-100 A
80-89 B
70-79 C
60-69 D
0-59 F

Write down a program that will take a student’s mark


as input and will convert it to the corresponding
letter grade. Assume that marks are integers.

31
THE END

32

You might also like