Chapter4 SelectionStructures
Chapter4 SelectionStructures
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
Repetition [Chapter 5]
}
CONDITIONS
Condition
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
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
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
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
switch statement
Syntax is more readable
)
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
In switch statements:
Make sure the controlling expression and case labels
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.
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.
45
FORMAT OF RECURSIVE FUNCTIONS
Recursive functions generally involve an if statement with the
following form:
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
1, n = 0
xn
x * x n-1, n>0
50
EXAMPLE 3: POWER FUNCTION (CONT’D)
#include <stdio.h>
int main(void) {
double x;
int n;