0% found this document useful (0 votes)
32 views51 pages

Chapter4 SelectionStructures

The document discusses selection structures in C programming, specifically if and switch statements. It covers conditions, relational and logical operators used in if statements. It explains the syntax of if statements with one and two alternatives using flowcharts. It also discusses nested if statements, switch statements, and implementing decision tables using if-else statements. The key aspects covered are control structures, conditions, relational operators, logical operators, if statements, nested if statements, switch statements, and common programming errors related to these structures.

Uploaded by

565
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views51 pages

Chapter4 SelectionStructures

The document discusses selection structures in C programming, specifically if and switch statements. It covers conditions, relational and logical operators used in if statements. It explains the syntax of if statements with one and two alternatives using flowcharts. It also discusses nested if statements, switch statements, and implementing decision tables using if-else statements. The key aspects covered are control structures, conditions, relational operators, logical operators, if statements, nested if statements, switch statements, and common programming errors related to these structures.

Uploaded by

565
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

SELECTION STRUCTURES:

IF AND SWITCH STATEMENTS


CHAPTER 4

1
OUTLINE
 Control Structures
 Conditions, Relational, and Logic Operators
 The if Statement and Flowchart
 if with Compound Statements
 Nested if statements
 The switch Statement
 Operator Precedence, Complementing a Condition
 Common Programming Errors
 Recursive Functions
CONTROL STRUCTURES
 Control structure
 Control the flow of execution in a program or a function

 Three kinds of control structures


 Sequence (Compound Statement)

 Selection (if and switch Statements)

 Repetition [Chapter 5]

 Selection control structure


 Chooses among alternative program statements
COMPOUND STATEMENT
A group of statements bracketed by { and }
 Executed Sequentially
A function body consists of a compound statement
{
statement1 ; Compound
Statement
statement2 ;
Specifies
. . . Sequential
statementn ; Execution

}
CONDITIONS
 Condition

 An expression that evaluates to false (0) or true (1)

 Conditions are used in if statements, such as:


if (a >= b)
printf("a is greater or equal to b");
else
printf("a is less than b");
 The condition in the above example: (a >= b)
RELATIONAL AND EQUALITY
OPERATORS
Operator Meaning Type
< less than relational
> greater than relational
<= less than or equal to relational
>= greater than or equal to relational
== equal to equality
!= not equal to equality

 Evaluate to either false (0) or true (1)


EXAMPLES OF RELATIONAL AND
EQUALITY OPERATORS
x i MAX y item mean ch num
-5 1024 1024 7 5.5 7.2 'M' 999

Operator Condition Value


<= x <= 0 true (1)
< i < MAX false (0)
>= x >= y false (0)
> item > mean false (0)
== ch == 'M' true (1)
!= num != MAX true (1)
LOGICAL OPERATORS
 Three Logical Operators
&& logical AND
|| logical OR
! logical NOT
 Truth Table for logical operators
A B (A && B) (A || B) !A
true true true true false
true false false true false
false true false true true
false false false false true
LOGICAL EXPRESSIONS
 Logical Expression
 Condition that uses one or more logical operators

salary children temperature humidity n


1050 6 38.2 0.85 101

Logical Expression Value


salary < 1000 || children > 4 true (1)
temperature > 35.0 && humidity > 0.90 false (0)
n >= 0 && n <= 100 false (0)
!(n >= 0 && n <= 100) true (1)
COMPARING CHARACTERS
 We can also compare characters in C
 Using the relational and equality operators

Expression Value
'9' >= '0' 1 (true)
'a' < 'e' 1 (true)
'B' <= 'A' 0 (false)
'Z' == 'z' 0 (false)
'A' <= 'a' 1 (true)
ch >= 'a' && ch <= 'z' ch is lowercase?
ENGLISH CONDITIONS AS C
EXPRESSIONS
English Condition Logical Expression
x and y are greater than z x > z && y > z

x is equal to 1 or 3 x == 1 || x == 3

x is in the range min to max x >= min && x <= max

x is outside the range z to y x < z || x > y


NEXT . . .
 Control Structures
 Conditions, Relational, and Logic Operators
 The if Statement and Flowchart
 if with Compound Statements
 Nested if statements
 The switch Statement
 Operator Precedence, Complementing a Condition
 Common Programming Errors
 Recursive Functions
if STATEMENT (ONE
ALTERNATIVE)
if (condition) statementT ;

if condition evaluates to true then statementT is

executed; Otherwise, statementT is skipped

Example:

if (x != 0.0)

product = product * x ;
if STATEMENT (TWO
ALTERNATIVES)
if (condition) statementT ;
else statementF ;
if condition evaluates to true then statementT is
executed and statementF is skipped; Otherwise,
statementT is skipped and statementF is executed
Example:
if (x >= 0.0) printf("Positive");
else printf("Negative");
FLOWCHARTS OF if
STATEMENTS

Two Alternatives One Alternative


if-else statement if statement
if WITH COMPOUND STATEMENTS

if (ch >= 'A' && ch <= 'Z') {


printf("Letter '%c' is Uppercase\n", ch);
ch = ch – 'A' + 'a';
printf("Converted to lowercase '%c'\n", ch);
}
else {
printf("'%c' is not Uppercase letter\n", ch);
printf("No conversion is done\n");
}
HAND TRACING AN if
STATEMENT
if (x > y) { /* switch x and y */
temp = x; /* save x in temp */
x = y; /* x becomes y */
y = temp; /* y becomes old x */
}
if statement x y temp Effect
12.5 5.0 ?
if (x>y) { 12.5>5.0 is true
temp = x ; 12.5 Store old x in temp
x = y ; 5.0 Store y in x
y = temp ; 12.5 Store old x in y
NEXT . . .
 Control Structures
 Conditions, Relational, and Logic Operators
 The if Statement and Flowchart
 if with Compound Statements
 Nested if statements
 The switch Statement
 Operator Precedence, Complementing a Condition
 Common Programming Errors
 Recursive Functions
NESTED IF STATEMENTS
 Nested if statement
 if statement inside another if statement
 Program decisions with multiple alternatives

 Example

if (x > 0)
num_pos = num_pos + 1;
else
if (x < 0)
num_neg = num_neg + 1;
else /* x equals 0 */
num_zero = num_zero + 1;
MULTIPLE-ALTERNATIVE DECISION
FORM
 The conditions are evaluated in sequence until a
true condition is reached
 If a condition is true, the statement following it is
executed, and the rest is skipped
if (x > 0)
num_pos = num_pos + 1;
More
else if (x < 0)
Readable
num_neg = num_neg + 1;
else /* x equals 0 */
num_zero = num_zero + 1;
SEQUENCE OF if STATEMENTS
 All conditions are always tested (none is skipped)
 Less efficient than nested if for alternative decisions

if (x > 0)
num_pos = num_pos + 1; Less
if (x < 0) Efficient
num_neg = num_neg + 1; than
if (x == 0) nested if
num_zero = num_zero + 1;
IMPLEMENTING A DECISION
TABLE
Use a multiple-alternative if statement to implement
a decision table that describes several alternatives

Salary Range ($) Base Tax % Excess


($)
0.00 to 14,999.99 0.00 15%
15,000.00 to 29,999.99 2,250.00 18%
30,000.00 to 49,999.99 5,400.00 22%
50,000.00 to 79,999.99 11,000.00 27%
80,000.00 to 150,000.00 21,600.00 33%
FUNCTION comp_tax
 Function comp_tax computes the tax based on the
tax table shown in the previous slide
FUNCTION comp_tax
(CONT'D)
ROAD SIGN DECISION
 Youare writing a program to control the warning
signs at the exists of major tunnels.

'S' means road is Slick or Slippery

temperature
ROAD SIGN NESTED if
STATEMENT
if (road_status == 'S')
if (temp > 0) {
printf("Wet roads ahead\n");
printf("Stopping time doubled\
n"); C associates else with the
} most recent incomplete if

else {
printf("Icy roads ahead\n");
printf("Stopping time
quadrupled\n");
}
else
NEXT . . .
 Control Structures
 Conditions, Relational, and Logic Operators
 The if Statement and Flowchart
 if with Compound Statements
 Nested if statements
 The switch Statement
 Operator Precedence, Complementing a Condition
 Common Programming Errors
 Recursive Functions
THE switch STATEMENT
 Can be used to select one of several alternatives
 Based on the value of a variable or simple expression
 Variable or expression may be of type int or char
 But not of type double
 Example: Display a message indicating the ship class
Class ID Ship Class
'B' or 'b' Battleship
'C' or 'c' Cruiser
'D' or 'd' Destroyer
'F' or 'f' Frigate
EXAMPLE OF
switch
STATEMENT
EXPLANATION OF switch
STATEMENT
 It takes the value of the variable class and compares
it to each of the cases in a top down approach.
 Itstops after it finds the first case that is equal to the
value of the variable class.
 It
then starts to execute each line following the
matching case till it finds a break statement.
 If
no case is equal to the value of class, then the
default case is executed.
 default case is optional. If no other case is equal to
the value of the controlling expression and there is
no default case, the entire switch body is skipped.
MORE ABOUT THE switch STATEMENT
 One or more C statements may follow a case label.
 You do not need to enclose multiple statements in
braces after a case label.
 You cannot use a string as a case label.
case "Cruiser": is not allowed
 Do not forget break at the end of each alternative.
 If the break statement is omitted then execution falls

through into the next alternative.


 Do not forget the braces of the switch statement.
NESTED if VERSUS switch
 Nested if statements
 More general than a switch statement

 Can implement any multiple-alternative decision

 Can be used to check ranges of values

 Can be used to compare double values

 switch statement
 Syntax is more readable

 Implemented more efficiently in machine language

 Use switch whenever there are few case labels

 Use default for values outside the set of case labels


NEXT . . .
 Control Structures
 Conditions, Relational, and Logic Operators
 The if Statement and Flowchart
 if with Compound Statements
 Nested if statements
 The switch Statement
 Operator Precedence, Complementing a Condition
 Common Programming Errors
 Recursive Functions
OPERATOR PRECEDENCE
Operator Precedence
function calls highest
! + - & (unary operators)
* / %
+ –
< <= >= >
== !=
&& (logical AND)
|| (logical OR)
= (assignment operator) lowest
EVALUATION TREE, STEP-BY-STEP EVALUATION

)
SHORT-CIRCUIT EVALUATION
 Stopping the evaluation of a logical expression as
soon as its value can be determined
 Logical-OR expression of the form (a || b)
 If a is true then (a || b) must be true, regardless of b
 No need to evaluate b
 However, if a is false then we should evaluate b

 Logical-AND expression of the form (a && b)


 If a is false then (a && b) must be false, regardless of b
 No need to evaluate b
 However, if a is true then we should evaluate b

 Canbe used to prevent division by zero


(divisor != 0 && x / divisor > 5)
LOGICAL ASSIGNMENT
 Use assignment to set int variables to false or true
 The false value is zero
C accepts any non-zero value as true
Examples of Logical Assignment
senior_citizen = (age >= 65);
even = (n%2 == 0);
uppercase = (ch >= 'A' && ch <= 'Z');
lowercase = (ch >= 'a' && ch <= 'z');
is_letter = (uppercase || lowercase);
COMPLEMENTING A
CONDITION
 DeMorgan's Theorem
!(expr1 && expr2) == (!expr1 || !expr2)
!(expr1 || expr2) == (!expr1 && !expr2)

Example Equivalent Expression


!(item == 5) item != 5
!(age >= 65) age < 65
!(n > 0 && n < 10) n <= 0 || n >= 10
!(x == 1 || x == 3) x != 1 && x != 3
!(x>y && (c=='Y' || c=='y')) (x<=y) || (c!='Y' && c!='y')
COMMON PROGRAMMING
ERRORS
 Do Not write: if (0 <= x <= 4)
0 <= x is either false (0) or true (1)
 Then, false(0) or true(1) are always <= 4
 Therefore, (0 <= x <= 4) is always true
 Instead, write: if (0 <= x && x <= 4)
 Do Not write: if (x = 10)
 = is the assignment operator

 x becomes 10 which is non-zero (true)

 if (x = 10) is always true


 Instead, write: if (x == 10)
MORE COMMON ERRORS
 In if statements:
 Don’t forget to parenthesize the if (condition)

 Don’t forget { and } in if with compound statements

 Correct pairings of if and else statements:


 C matches else with the closest unmatched if

 In switch statements:
 Make sure the controlling expression and case labels

are of the same permitted type (int or char)


 Remember to include the default case

 Don’t forget { and } for the switch statement

 Don’t forget the break at the end of each case


int Day;
OR:
printf("Enter a number from 1 to 7 > "); int Day;
scanf("%d",&Day); printf("Enter from 1 to 7 >");
scanf("%d",&Day);
if (Day==1)printf("Today is sunday"); ;
else if (Day==2)printf("Today is Monday"); switch(Day){
else if (Day==3)printf("Today is tuesday"); case 1:printf("Today is Sunday");
else if (Day==4)printf("Today is wendsday"); break;
else if (Day==5)printf ("Today is thursday"); case 2:printf("Today is Monday");
else if (Day==6)printf("Today is friday"); break;
else if (Day==7)printf("Today is saturday"); case 3: printf("Today is Tuseday");
break;
else printf("Input a number from 1 to 7"); case 4: printf("Today is Wendsday");
return(0); break;
case 5: printf("Today is Thursaday");
break;
default: ("Enter a number from 1to 7");
}

41
int x=20, i;
printf("Enter a number");
scanf("%d",&i);

switch(i){
case 1 :
case 2:
case 3:
x=x+1;
printf("%d",x);
break;
case 6:
case 8:
x=x+2;
printf("%d",x);
break; 42
default: x=x+3;
printf("%d",x);

}
Write a program to find the largest of three
numbers entered by the user.
For example, if user enters 2, 6, 8
Your answer should display, 8 is the largest
number

#include<stdio.h>

int main(){
int x,y,z;
printf ("Enter > ");
scanf("%d%d%d",&x,&y,&z);
if (x>y && x>z)
printf("The largest number is %d",x);
else if (y>x && y>z)
printf("The largest number is %d",y);
else if (z>y && z>x)
printf("The largest number is %d",z); 43
return 0;
}
RECURSIVE FUNCTIONS
• We have seen so far that a function, such as main, can call another function to perform
some computation.

• In C, a function can also call itself. Such types of functions are called recursive functions.

• A function, f, is also said to be recursive if it calls another function, g, which in turn calls f. In
this case f and g are called mutually recursive functions.

• Many mathematical functions are defined recursively.


• For example, the factorial function is defined mathematically as:

1, n = 0
n! =
n (n-1)! , n > 0

• Although recursive functions are usually less efficient than iterative functions (functions
that use loops) due to overhead in function calls, in many cases, recursive functions provide
more natural and simple solutions.

• Thus, recursion is a powerful tool in problem solving and programming. 44


INTRODUCING RECURSIVE FUNCTIONS (CONT’D)
 Problems that can be solved using recursion have the
following characteristics:
 One or more simple cases of the problem that have a direct and easy
answer – also called base cases. Example: 0! = 1.
 The other cases can be re-defined in terms of a similar but smaller
problem - recursive cases. Example: n! = n (n-1)!
 By applying this re-definition process, each time the recursive case(s)
will move closer and eventually reach the base case(s). Example: n! 
(n-1)!  (n-2)!  . . . 1!, 0!.

 The strategy in recursive solutions is called divide-and-conquer. The idea is


to keep reducing the problem size until it reduces to the simple case which
has an obvious solution.

45
FORMAT OF RECURSIVE FUNCTIONS
 Recursive functions generally involve an if statement with the
following form:

if this is a simple case


solve it
else
redefine the problem using recursion

 The if-branch is the base case, while the else-branch is the


recursive case.

 The recursive step provides the repetition needed for the


solution and the base step provides the termination.

 Note: For the recursion to terminate, each recursive case


must be moving closer to a base case with each recursive call.
46
EXAMPLE 1: RECURSIVE FACTORIAL
 Thefollowing shows the recursive and iterative
versions of the factorial function:
Recursive version Iterative version
long int factorial (int n) long int factorial (int n)
{ {
if (n == 0) int i, product=1;
return 1; for (i=n; i>1; --i)
else product=product * i;
return n * factorial (n-1);
} return product;
}

Recursive Call
47
THE COMPLETE RECURSIVE FACTORIAL EXAMPLE
/* Computes the factorial of a number */ /* Computes n! for n greater than or equal
#include <stdio.h> to zero */
long int factorial(int n); long int factorial (int n)
{
/* shows how to call a user-define function */ if (n == 0) //base case
int main(void) { return 1;
int num, fact; else
printf("Enter an integer between 0 and 7: "); return n * factorial (n-1); //recursive
scanf("%d", &num);
//case
if (num < 0)
}
printf("Factorial not defined for negative numbers\n");
else if (num <= 7) {
fact = factorial(num);
printf("The factorial of %d is %d\n", num, fact);
} else
printf("Number out of range: %d\n", num);

system("pause");
return 0; 48
}
TRACING RECURSIVE FUNCTIONS
• Executing recursive algorithms goes through two phases:
 Expansion in which each recursive step is applied until reaching a base step
 “Substitution” in which the solution is constructed backwards starting with the base step(s)

Expansion
factorial(4) = 4 * factorial (3)
phase
= 4 * (3 * factorial (2))

= 4 * (3 * (2 * factorial (1)))

= 4 * (3 * (2 * (1 * factorial (0))))

= 4 * (3 * (2 * (1 * 1)))

= 4 * (3 * (2 * 1))

= 4 * (3 * 2)

=4*6 Substitution
phase
= 24

49
EXAMPLE 2: POWER FUNCTION

• Suppose we wish to define our own power function that raises


a double number to the power of a non-negative integer
exponent. xn , n >= 0.

• The base case is if n is 0. The answer is 1.

• The recursive case is: xn = x * xn-1.

1, n = 0
xn
x * x n-1, n>0
50
EXAMPLE 3: POWER FUNCTION (CONT’D)
#include <stdio.h>

double pow(double x, int n);

int main(void) {
double x;
int n;

printf("Enter double x and integer n to find pow(x,n): ");


scanf("%lf%d", &x, &n);

printf("pow(%f, %d) = %f\n", x, n, pow(x, n));


system("pause");
return 0;
}

double pow(double x, int n) {


if (n == 0)
return 1; /* simple case */
else 51
return x * pow(x, n - 1); /* recursive step */
}

You might also like