Unit2 ControlStructures
Unit2 ControlStructures
Control Structures
Mark Redekopp
2
Announcements
• Lab 2 – Due Friday
3
Review
• Write a program to ask the user to enter two integers
representing hours then minutes. Output the
equivalent number of seconds.
• To get started…
– Go to http://bytes.usc.edu/cs103/in-class-exercises
• printseconds
– We've started the program for you…look at the
• General template for a program with the #includes, using
namespace std; and int main() function which returns 0
– We've declared variables where you can store the input
and computation results
– Now you add code to
• Get input from the user
• And compute the answer and place it in the 'sec' variable
4
If..else statements
MODULE 5: CONDITIONAL
STATEMENTS
5
Comparison Operators
• Control structures like if, while, and for require conditions to
determine what code should execute
• To perform comparison of variables, constants, or expressions
in C/C++ we can use the basic 6 comparison operators
Operator(s) Meaning Example
== Equality if(x == y)
!= Inequality if(x != 7)
A B AND A B OR A NOT
False False False False False False False True
False True False False True True True False
True False False True False True
True True True True True True
7
Exercise
• Which of the following is NOT a condition to check if
the integer x is in the range [-1 to 5]
• x >= -1 && x <= 5
• -1 <= x <= 5
• !( x < -1 || x > 5)
• x > -2 && x < 6
8
// following statements
If Block Else
Statements Block Statements
Following
statements
11
If…Else If…Else
• Use to execute only if (condition1)
{
certain portions of code // executed if condition1 is true
}
• else if is optional else if (condition2)
{
– Can have any number of // executed if condition2 is true
// but condition1 was false
else if statements }
• else is optional else if (condition3)
{
// executed if condition3 is true
• { … } indicate code // but condition1 and condition2
associated with the if, }
// were false
else if if (condition1)
{
// executed if condition1 is True
}
else if (condition2)
{
// executed if condition2 is True
True False
condition // but condition1 was False
}
1 else
if (condition1)
If Block Else
If BlockIf Else
Else {
Statements Block Statements // executed if condition1 is True
Statements Statements Statements
}
else
{
Following if (condition2){
statements // executed if condition2 is True
// but condition1 was False
}
else
Following {
// executed if neither condition
Statements // above is True
}
}
13
Rule/Exception Idiom
• Name: Rule/Exception // Default action
Example
16
}
else if( /* Condition 2 */ )
Customer Service Call Menu {
// Case 2 code
Exercises
• Conditionals In-Class Exercises
– discount
– weekday
– nth
19
? Operator
• A simple if..else statement can be expressed with the
? operator
– int x = (y > z) ? 2 : 1;
– Same as:
if(y > z) x = 2;
else x = 1;
• Syntax: (condition) ? expr_if_true : expr_if_false;
• Meaning: the expression will result/return
expr_if_true if condition evaluates to true or
expr_if_false if condition evaluates to false
24
int main()
task but do so in a concise {
cout << 1 << endl;
way cout << 2 << endl;
...
– Print out all numbers 1-100 cout << 100 << endl;
return 0;
– Keep taking turns until a }
game is over #include <iostream> Assume this performs
• Imagine the game of 'war'…it using namespace std; code to "take a turn"
and thenproduces a
never ends!! int main()
true/false result
indicating if the game
{
• We could try to achieve bool gameOver;
is over
gameOver = take_turn();
these without loops, but… if( ! gameOver ){
gameOver = take_turn();
if( ! gameOver ) {
...
{
}
}
26
False
• Body (cout << i << endl;)
– Code to repeat for each iteration
Update Statement
• Update (e.g. i += 1)
– Modify the variable(s) related to the
condition Code after the loop
27
False
while (i < 1000) (cout << i << endl;)
{
cout << i << endl;
i++; Update Statement
} (e.g. i += 1)
// following statements
Code after the loop
While loop printing 0 to 999
28
while Loop
// guessing game
• One way to think of a while bool guessedCorrect = false;
if( !guessedCorrect )
loop is as a repeating 'if' {
guessedCorrect = guessAgain();
statement }
// want to repeat if cond. check again
• When you describe a if( !guessedCorrect )
{
problem/solution you use guessedCorrect = guessAgain();
} // want to repeat if cond. check again
the words 'until some
condition is true' that is the An if-statement will only execute once
same as saying 'while some
// guessing game
condition is not true' bool guessedCorrect = false;
– "Until they guess correctly" is while( !guessedCorrect )
{
the same as "while they do guessedCorrect = guessAgain();
NOT guess correctly" }
Do..While Loop
Accept Guess Draw out a flow chart of the
desired sequence and look
for the repetitive sequence
Correct
Here we check at the end
False to see if we should
repeat…perfect for a
Accept Guess
do..while loop
do
True Correct
{ accept_guess }
False while ( ! correct )
Accept Guess
Correct
False
Post-Loop
Code
31
While loop
do..while loop
Correct
while loop
Correct
do True
True { accept_guess }
False while ( ! correct ) Accept Guess
Accept Guess But a while loop
checks at the
beginning of the
Correct loop, so we must Post-Loop
accept one guess Code
False
before starting:
accept_guess
Post-Loop while( ! correct )
Code { accept_guess }
32
{
– performs initialization 3 6
// executed if condition is true
} // go to top, do update, eval cond. again
statement once
9 // following statements
– checks the condition // only gets here when cond. is false
for Loop
for(init stmt; cond; update stmt)
{
• Initialization stmt executed first // body of loop
}
• Cond is evaluated next
• Body only executed if cond. is true // Outputs 0 1 2 3 4 (on separate lines)
for(i=0; i < 5; i++){
• Update stmt executed }
cout << i << endl;
Map Idiom
• Name: Map for(/* loop thru each input */)
{
• Description: Convert (map) // Get next input, x
// Produce next output, f(x)
each value in a collection to }
another value
Structure
• Structure: Use a loop to
Output the first n odd integers
process a series of input values Input: 0, 1, 2, ..., n-1
and convert to the desired Output: 1, 3, 5, , 2(n-1)+1
output values Given a threshold of 70, indicate if
– Usually with a n-to-n input- students have passed a quiz
output relationship Input: 78, 61, 85, 93, 54
Output: T, F, T, T, F
• Example(s):
– See examples on the right Take the absolute value of each input
Input: -18, -13, 36, 2, -21
Output: 18, 13, 36, 2, 21
37
Reduce Idiom
• Name: Reduce / Combine / // Declare reduction variable, r
// Set r to identity value
Aggregate
for(/* loop thru each input */)
• Description: Combine/reduce all {
elements of a collection to a // Get next input, x
// Update r using x
single value }
• Structure: Use a "reduction" Structure
variable and a loop to process a
series of input values, combining Average a series of 4 numbers
each of them to form a single (or Input: 2, 3, 1, 8
Average: 3.5
constant number of) output value double sum = 0;
in the reduction variable double x;
for(int i=0; i < 4; i++)
– An n-to-1 input-output relationship { cin >> x;
• Example(s): sum += x;
}
– See example on the right cout << sum / 4.0 << endl;
38
Selection Idiom
• Name: Selection // declare/initialize any state variables
// needed to track the desired result
• Description: Select a subset // loop through each instance
(possibly one or none) of for( /* each input, i */ ) {
// Check if input meets the property
elements from a collection if(property is true for i) {
// Update state (variables) as needed
based on a particular property }
}
• Structure: Loop through each // Output the state variables
element and check whether it Structure
meets the desired property. If
so, perform a map, reduce, or Count Positive Integers
other other update operation. Input: 2, -3, -1, 8
Output: 2
• Example(s):
– Count all positive integers inputs
39
Exercises
• In-class exercises:
– countodd
– liebnizapprox
– wallis
– revdigits
40
Loop Practice
• Write a for loop to compute the first 10 terms of
the Liebniz approximation of π/4:
• π/4 = 1/1 – 1/3 + 1/5 – 1/7 + 1/9 …
• Tip: write a table of the loop counter variable vs. desired
value and then derive the general formula
• In-class exercise:
– liebnizapprox
Counter (i) Desired Pattern Counter (i) Desired Pattern
0 +1/1 for(i=0;i<10;i++) 1 +1/1 for(i=1; i<=19; i+=2)
1 -1/3 Fraction: 3 -1/3 Fraction:
2 +1/5 5 +1/5
… … +/- => … … +/- =>
9 -1/19 19 -1/19
41
Loop Practice
• Write for loops to compute the first 10 terms of
the following approximations:
– ex: 1 + x + x2/2! + x3/3! + x4/4! …
• Assume 1 is the 1st term and assume functions
– fact(int n) // returns n!
– pow(double x, double n) // returns xn
– Wallis:
• π/2 = 2/1 * 2/3 * 4/3 * 4/5 * 6/5 * 6/7 * 8/7 …
• In-class Exercise
– wallisapprox
42
smaller pieces
43
TRACING EXECUTION 1
44
cout << "For 2: " << endl; cout << "For 3: " << endl; cout << "For 4: " << endl;
for(i=0; i < 5; i++){ for(i=0; i < 20; i+=j){ for(i=10; i > 0; i--){
cout << 2*i+1 << " "; cout << i << " "; cout << i+j << " ";
} j++; i = i/2; j = j*2;
cout << endl; } }
cout << endl; cout << endl;
int i = 3; double T = 8;
char c = 'a';
cout << "For 6: " << endl;
cout << "For 5: " << endl; for(i=0; i <= T; i++){
for( ; c <= 'j'; c+=i ){ // Force rounding to 3 decimal places
cout << c << " "; cout << fixed << setprecision(3);
} // Now print the number
cout << endl; cout << sin(2*M_PI*i/T) << endl;
}
break statement
• break
– Ends the current loop [not if statement] immediately and continues
execution after its last statement
• Consider two alternatives for stopping a loop if an
invalid (negative) guess is entered
bool done = false; bool done = false;
while ( done == false ) { while ( done == false ) {
cout << "Enter guess: " << endl; cout << "Enter guess: " << endl;
cin >> guess; cin >> guess;
if( guess < 0 ) if( guess < 0 )
done = true; break;
} }
else { // Process guess
// Process guess // If guess < 0 we would skip this
} }
}
51
continue statement
• continue
– Ends the current loop [not if statement] immediately and
continues execution after its last statement
• Consider two alternatives for repeating a loop to get a
new guess if an invalid (negative) guess is entered
– Often continue can be eliminated by changing the if
condition
bool done = false; bool done = false;
while ( done == false ) { while( done == false) {
cout << "Enter guess: " << endl; cout << "Enter guess: " << endl;
cin >> guess; cin >> guess;
if( guess >= 0 ) { if(guess < 0){
// Process Guess continue;
} }
} // Process guess (only here if guess>=0)
}
52
while(sum > 0)
sum = sum/2;
NESTED LOOPS
56
False init
condition False
condition
True What code can we put True
while Block in the body of a For Block
loop?
Statements Statements
Following Update
statements
Following
57
Cond1: T T F False
cond1
while (cond1) { 1 9 15
// code1 2 10 True
Cond2: T T F
while(cond2) { 3 5 7 11 13 code1
Cond2: T F // code 2 12
4 6 False
}
// code3 8 14 cond2
} True
16 code2
code3
Following
statements
58
1 game
(and we repeat that {
1 turn
cout << "Enter guess: ";
over and over) cin >> guess;
}
– The body of the inner cout << "Win!" << endl;
cout << "Play again (y/n): ";
loop represents 1 turn cin >> again;
(and we repeat turn }
return 0;
after turn) }
59
Nested Loops
• Inner loops execute fully (go through every iteration before the
next iteration of the outer loop starts)
#include <iostream>
using namespace std;
int main()
{
for(int i=0; i < 2; i++){ Output:
for(int j=0; j < 3; j++){
Nested Loops
• Write a program using nested
#include <iostream>
loops to print a multiplication
table of 1..12 using namespace std;
Nested Loops
• Tip: Decide what abstract "thing"
#include <iostream>
your iterating through and read
the for loop as "for each thing" … using namespace std;
Nested Loops
• Use the setw I/O manipulator
#include <iostream>
to beautify the output #include <iomanip>
using namespace std;
int main()
{
for(int r=1; r <= 12; r++){
for(int c=1; c <= 12; c++){
cout << setw(4) << r*c;
}
cout << endl;
}
return 0;
}
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
63
#include Directive
• Common usage: To include “header files” that allow us to
access functions defined in a separate file or library
• For pure C compilers, we include a C header file with its
filename: #include <stdlib.h>
• For C++ compilers, we include a C header file without the .h
extension and prepend a ‘c’: #include <cstdlib>
C Description C++ Description
stdio.h C Input/Output/File access (printf, iostream I/O and File streams (cin, cout, cerr)
cstdio fopen, snprintf, etc.)
stdlib.h rand(), Memory allocation, etc. fstream File I/O (ifstream, ofstream)
cstdlib
string.h C-string library functions that operate string C++ string class that defines the ‘string’
cstring on character arrays object
math.h Math functions: sin(), pow(), etc. vector Array-like container class
cmath
68
SOLUTIONS
71
Loop Practice
• Write a for loop to compute the first 10 terms of
the Liebniz approximation of π/4:
• π/4 = 1/1 – 1/3 + 1/5 – 1/7 + 1/9 …
• Tip: write a table of the loop counter variable vs. desired
value and then derive the general formula
Tracing Answers
For 1: While loop 1:
0 1 2 3 4 15 15 4
11 3
For 2: 8 2
1 3 5 7 9 6 1
For 6:
0.000
0.707
1.000
0.707
0.000
-0.707
-1.000
-0.707
-0.000