Title: Control Structures
1Control Structures
2Chapter Objective
- Selection Structures that allow us to provide
alternative paths in a program. - Repetition Structures that allow us to repeat a
set of steps as long as a condition is true. - Algorithm development and descriptions of
algorithms. - Three common forms of input loops
3Algorithm Devolopement
- Read the problem and define a solution.
- Draw a flowchart describing the steps of the
solution which is nothing but The Algorithm - Construct a Pseudo Code from the flowchart of the
above step. - Write The Actual Code in programming language.
4Flowchart
Time 0
Is Time lt 10?
Compute Velocity
Print Velocity
Increment Time by 1
5Pseudo Code
- Set Time to 0
- While Time lt 10
- Compute velocity
- Print Velocity
- Increment Time by 1
- Importance of writing a pseudo code is that it
simplifies the development of actual code in PL.
6Conditional Expressions
- Both Selection Repetition use conditions.
- A condition is an expression that can be
evaluated to True or False. - It is composed of expressions combined with
Relational Operators or Logical Operators. - There can be multiple operators and multiple
expressions in a single conditional statement.
7Relational Operators
- lt is less than
- lt is less than or equal to
- gt is greater than
- gt is greater than or equal to
- is equal to
- ! is not equal to
- a lt 5
- x y gt 10.5
- cos(denominator) lt 0.25
8Relational Operators (cont.)
- Given the value of identifiers, we can evaluate
them to be true or false. - In C, a true condition is assigned a value 1
while a false condition is 0. - d b gt c
- Note Blanks can be used on either side of a
relational operator, but blanks cannot be used to
separate a two-character operator such as . - For readability use spaces around the relational
operators in an expression but not around the
arithmetic operators in the conditions.
9Logical Operators
- Logical Operators compare conditions and not
expressions although can be used within
conditions. - And
- Or
- Not !
- (a lt b b lt c)
10Logical Operators (cont)
- If A B are conditions then the logical
operators can be used to generate new conditions
A B, A B, !A, !B. - Truth table for Logical Operators
11Precedence Associativity
- Relational Operators have higher precedence over
Logical Operators (except Not Operator) - Arithmetic Operators have higher precedence over
relational and logical operators.
12Some Complex Conditions
- a 5.5 b 1.5 k 3
- a lt 10.0 k
- !(a 3b)
- -k gt k6
- a lt 10 a gt 5
- fabs(k) gt 3 k lt b-a
- k ! a-b
- TRUE
- TRUE
- FALSE
- TRUE
- FALSE
- TRUE
13Selection Statements
- The if statement allows us to test conditions and
then perform statements based on whether the
conditions are true or false. - There are two forms
- The simple if statement.
- The if-else statement.
- The switch statement allows us to test multiple
conditions and then execute group of statements
based on whether the conditions are true or false.
14The simple if statement
- if (condition)
- statement 1
- if (condition)
-
- statement 1
- statement 2
- .
- statement n
Is Condition True
Is Condition True
Is Condition True
Is Condition True
Is Condition True
Is Condition True
statement 1
statement 1
statement 1
statement 1
Is Condition True
statement 1
statement 2
statement n
15Example
- // The simple if statement example
- include ltiostream.hgt
- using namespace std
- int main()
-
- int a, count0, sum0
- cout ltlt Enter Number a
- cin gtgt a
- if (alt10)
-
- count count 1
- sum sum a
-
- cout ltlt \nCount ltlt count
- cout ltlt \nSum ltlt sum
- return 0
16The if-else statement
- if (condition)
- statement 1
- else
- statement 2
Is Condition True
statement 1
statement 2
17Example
- // The if-else statement example
- include ltiostream.hgt
- using namespace std
- int main()
-
- int x,y,z,i0,j0,k0
- cout ltlt Enter values for X,Y,Z
- cin gtgt x gtgt y gtgt z
- if (xgty)
- if (y lt z)
- i i 1
- else
- j j 1
- else
- k k 1
- cout ltlt \nI ltlt i ltlt , J ltlt j ltlt K
ltlt k - return 0
18The switch statement
- The switch statement is used for multiple
selection decision making. - It is often used to replace nested if-else
statements. - The syntax of switch statement is as follows
- switch (controlling expression)
-
- case label1
- statements
- case label2
- statements
- .
- default
- statements
19Example
- include ltiostream.hgt
- using namespace std
- int main()
-
- int code
- cout ltlt Enter Code Between 10 12
- cin gtgt code
- if (code 10)
- cout ltlt You Entered 10
- else
- if (code 11)
- cout ltlt You Entered 11
- else
- if (code 12)
- cout ltlt You Entered 12
- else
- cout ltlt Number Invalid
- return 0
include ltiostream.hgt using namespace std int
main() int code cout ltlt Enter Code Between
10 12 cin gtgt code switch (code)
case 10 cout ltlt You Entered 10
break case 11 cout ltlt You
Entered 11 break case 12
cout ltlt You Entered 12 break
default cout ltlt Number
Invalid break return 0
20Loop Structures
- Loops are used to implement repetitive
structures. - C has 3 loop structures namely while loop,
the do while loop and the for loop. - To modify loop's performance we have 2 more
statements break and continue.
21The while Loop
- while (condition)
- statement
- The while statement allows a program to
repeatedly execute a block of statements while
the specified condition is true. - The condition is evaluated first before the
statements within the loop are executed. - An infinite loop is generated if the condition
is always true.
Is Condition True
Is Condition True
Is Condition True
Is Condition True
Is Condition True
Is Condition True
statement 1
statement 1
statement 1
statement 1
22Example
- // The while Loop example
- include ltiostream.hgt
- using namespace std
- int main()
-
- double PI 3.141593
- int degrees 0
- double radians
- //Print radians degrees in a loop.
- while (degrees lt 360 )
-
- radians degrees PI / 180
- cout ltlt Degrees ltlt degrees ltlt Radians
ltlt radians - degrees
-
- return 0
23The do-while Loop
- do
-
- statements
-
- while (condition)
- The do-while loop is similar to the while loop
except that the condition is tested at the end
instead of at the beginning. - The statements execute at least once.
Statement Block
Is Condition True
Is Condition True
Is Condition True
Is Condition True
Is Condition True
Is Condition True
Statement
24Example
- // The do-while Loop example
- include ltiostream.hgt
- using namespace std
- int main()
-
- double PI 3.141593
- int degrees 0
- double radians
- //Print radians degrees in a loop.
- do
-
- radians degrees PI / 180
- cout ltlt Degrees ltlt degrees ltlt Radians
ltlt radians - degrees
- while (degrees lt 360 )
- return 0
25The for Loop
- for (expression_1 expression_2 expression3)
-
- statements
-
- Used when we need to loop using a counter that
increments or decrements. - First expression initializes the loop variable.
- Second expression specifies the condition for
loop to execute. - Third expression increments or decrements the
loop variable.
Initialize Loop Variable Modify Loop
Variable
Condition
Statement Block
26Example
- // The for Loop example
- include ltiostream.hgt
- using namespace std
- int main()
-
- double PI 3.141593
- double radians
- //Print radians degrees in a loop.
- for (int degrees 0degrees lt 360 degrees)
-
- radians degrees PI / 180
- cout ltlt Degrees ltlt degrees ltlt Radians
ltlt radians -
- return 0
27The break continue Statements
- The break statement is used to immediately exit
from the loop. - The continue statement is used to skip the
remaining statements in the current pass and jump
to the next iteration. - Thus break and continue are used to exit the
current iteration or the entire loop itself.
sum 0 for( int k1 klt20 k) cin gtgt
x if (x gt 10.0) continue sum
x cout ltlt Sum ltlt sum ltlt endl
sum 0 for( int k1 klt20 k) cin gtgt
x if (x gt 10.0) break sum x cout ltlt
Sum ltlt sum ltlt endl
28Input Structures
- Loops are often required for reading data from
the keyboard or from the data file. - There are three common forms of input loops
- Counter-controlled loop
- Sentinel-controlled loop
- End-of-data loop
29Counter-controlled Loop
- Used to read input data if value is known before
the data is entered. - The number of data values to be input is read
from the keyboard and stored in a counter. - The counter is then used to control the no. of
iterations of the loop.
30Counter-controlled Loop (cont)
Input counter
i lt- 0 i
False
i lt counter
True
Input Data Value
31Example
- include ltiostream.hgt
- using namespace std
- int main()
-
- double exam_score, sum 0, average
- int counter
- cout ltlt Enter Number of Exam Scores to be
input. - cin gtgt counter
- cout ltlt Enter ltlt counter ltlt exam scores
separated by whitespace - for (int i1 iltcounter i)
-
- cin gtgt exam_score
- sum sum exam_score
-
- average sum / counter
- cout ltlt counter ltlt students took the exam.\n
- cout ltlt The exam average is ltlt average ltlt
endl - return 0
32Sentinel-controlled Loop
- Used to read input data if a special data value
exists. - That value can be used to indicate end of data.
- Also it must be a value that cannot occur
naturally in the input data.
33Sentinel-controlled Loop (cont)
Input data_value
data_value ! sentinel
False
True
Input next Data_value
34Example
- include ltiostream.hgt
- using namespace std
- int main()
-
- double exam_score, sum 0, average
- int count 0
- cout ltlt Enter exam scores separated by
whitespace.\n - cout ltlt Enter a negative value to indicate end
of data.\n - cin gtgt exam_score
- while (exam_score gt 0)
-
- sum sum exam_score
- count
- cin gtgt exam_score
-
- average sum / count
- cout ltlt count ltlt students took the exam.\n
- cout ltlt The exam average is ltlt average ltlt
endl - return 0
35End-of-data Loop
- Most flexible loop for inputting data.
- The loop is structured to continue executing
statements while new data is available. - No prior knowledge of number of data values or a
sentinel value is required. - Execution of loop terminates when end of data is
encountered.
36End-of-data Loop (cont)
Input data_value
! end_of_data
False
True
Input next data_value
37Example
- include ltiostream.hgt
- using namespace std
- int main()
-
- double exam_score, sum 0, average
- int count 0
- cout ltlt Enter exam scores separated by
whitespace.\n - cout ltlt Enter a negative value to indicate end
of data.\n - cin gtgt exam_score
- while (!cin.eof())
-
- sum sum exam_score
- count
- cin gtgt exam_score
-
- average sum / count
- cout ltlt count ltlt students took the exam.\n
- cout ltlt The exam average is ltlt average ltlt
endl - return 0
38An Engineering Problem
- Problem Statement
- Using the polynomials that represent the altitude
and velocity for a weather balloon, print a table
using units of meters and meters per second. Also
find the maximum altitude (or height) and its
corresponding time.
39An Engineering Problem (cont)
- I/O Description
- The user will input the starting time, time
increment and ending time for a table. - The output is the table of altitude and velocity
values and the maximum altitude and its
corresponding time. - We will use double as a data type for our input
and output values.
Starting Time
Table of Velocities and Acceleration
Time increment
Maximum Height and its Time
Ending Time
40An Engineering Problem (cont)
- An Example
- Assume starting time is 0 hours, the time
increment is 1 hour and ending time is 5 hours. - We need to divide the velocity value in meters
per hours by 3600. - We get following values
41An Engineering Problem (cont)
- Algorithm Development
- Get user input to specify times for the table.
- Generate and print conversation table and find
the maximum height and corresponding time. - Print maximum height and corresponding time.
42An Engineering Problem (cont)
- Pseudocode
- mainread initial, increment, final values from
keyboard - set max_height to zero
- set max_time to zero
- print table heading
- set time to initial
- while time lt final
- compute height and velocity
- print height and velocity
- if height gt max_height
- set max_height to height
- set max_time to time
- add increment to time
- print max_time and max_height
43An Engineering Problem (cont)
- Testing
- Enter initial value for table (in hours)
- 0
- Enter increment between lines (in hours)
- 1
- Enter final value for table (in hours)
- 5
- Weather Balloon Information
- Time Height Velocity
- (hrs) (meters) (meters/s)
- 0 220.00 1.14
- 1 3951.88 0.94
- 2 6994.08 0.76
- 3 9414.28 0.59
- 4 11277.28 0.45
- 5 12645.00 0.32
- Maximum balloon height was 12645.00 meters and it
occurred at 5.00 hours