h2 Control
h2 Control
Cecia Chan
Brian Mak
Dimitris Papadopoulos
Pedro Sander
Charles Zhang
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.1
Introduction
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.2
Part I
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.3
if Statement
Syntax: if Statement
if (<boolean expression>) <statement>
if (<boolean expression>) { <sequence of statements> }
true
int x;
cin >> x;
statements if (x < 0)
{
x = -x;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.4
Example: To Sort 2 Numbers
#include <iostream> /* File: [Link] */
using namespace std;
if (x > y)
{
temp = x; // Save the original value of x
x = y; // Replace x by y
y = temp; // Put the original value of x to y
}
boolean
Example: To find the larger value.
expression
false true
int x, y, larger;
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.6
if-else-if Statement
if (<bool-exp>) { <stmts> }
else if (<bool-exp>) { <stmts> }
else if (<bool-exp>) { <stmts> }
..
.
else { <stmts> }
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.7
Example: Conversion to Letter Grade
#include <iostream> /* File: [Link] */
using namespace std;
cout << "Your letter grade is " << grade << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.8
Relational Operators
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.9
Logical Operators
Logical operators are used to modify or combine boolean
values.
C++ has 3 logical operators:
!: logical NOT
||: logical OR
&&: logical AND
Boolean values
true: internally represented by 1; ANY non-zero number is also
considered true
false: internally represented by 0
p q !p p && q p || q
T T F T T
T F F F T
F T T F T
F F T F F
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.10
Precedence and Associativity of Boolean Operators
Example
/* Example: get the larger of two numbers */
larger = (x > y) ? x : y;
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.13
Nested if
if (condition1)
{
if (condition2)
if (condition3)
cout "conditions 1,2,3 are true." endl;
else
cout "conditions 1,2 are true." endl;
else
cout "condition1 true; condition2 false." endl;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.14
“Dangling else” Problem
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.15
“Dangling else” Problem ..
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.16
Part II
Loops or Iterations
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.17
while Loop (Statement)
Syntax: while Statement
while (<bool-exp>) { <stmts> }
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.20
Example: Find the Maximum using while Loop
#include <iostream> /* File: [Link] */
using namespace std;
cout << endl << "The maximum number = " << max << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.21
Example: Continuously Halving a float Number
#include <iostream> /* File: [Link] */
using namespace std;
int main()
{
int count = 0; // Count how many times that x can be halved
float x; // Number to halve
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.22
Example: Continuously Halving a float Number ..
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.23
Example: Continuously Halving an int Number
#include <iostream> /* File: [Link] */
using namespace std;
int main()
{
int count = 0; // Count how many times that x can be halved
int x; // Number to halve
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.24
Example: Continuously Halving an int Number ..
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.25
A Good Programming Practice on Loops
After you have written the codes for a loop, try verifying the
following cases:
The first iteration.
The second iteration.
The last iteration.
Do you know exactly how many iterations will be performed?
How can the loop terminate? Otherwise, you have an infinite
loop! And the program runs forever!
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.26
for Loop (Statement)
Syntax: for Statement
for (<for-initialization> ; <bool-exp> ; <post-processing>)
{ <stmts> }
cout << number << "! = " << factorial << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.28
Example: x n using for Loop
#include <iostream> /* File: [Link] */
using namespace std;
if (n < 0)
cerr << "Error: n < 0!" << endl;
else
{
for (int j = 1; j <= n; j++)
result *= x;
cout << x << " to the power of " << n << " = " << result << endl;
}
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.29
Remarks on for Statement
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.30
Part III
Nested Looooooops
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.31
Nested Loops Example: Compute Average Score
One may put a while loop inside another while loop.
#include <iostream> /∗ File: [Link] ∗/
using namespace std;
int main( )
{
int NUM ASSIGNMENTS = 5; // Uppercase variable doesn’t change
int j; // Assignment counter
int score, sum of scores;
char reply = ’y’; // ’y’ for yes, ’n’ for no; initialized to yes
cout "Enter scores for the first student? (y/n) " endl;
while ((cin reply) && (reply == ’y’ || reply == ’Y’))
{
sum of scores = 0; // Reset the accumulator to zero
j = 1; // Reset the assignment counter to 1
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.32
Nested Loops Example: Multiplication Table
int main()
{
// To print out products of j*k where j, k = 1,...,10
for (int j = 1; j <= 10; ++j)
{
for (int k = 1; k <= 10; ++k) // Reset k=1 for each j. Why?
cout << setw(4) << j*k; // Set the length of output field to 4
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.33
break and continue
A break causes the innermost enclosing loop to exit
immediately.
A continue causes the next iteration of the enclosing loop to
begin.
That is, in the while loop, control passes to test the boolean
expression again immediately.
statements 2 statements 2
false false
true
boolean true boolean
expression 2 statements 3 expression 2
continue
false false
break
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.34
Example: Stop Inputs with break
#include <iostream> /* File: [Link] */
using namespace std;
int main()
{
int NUM_ASSIGNMENTS = 5; // Uppercase variable doesn’t change
int j; // Assignment counter
int score, sum_of_scores;
char reply = ’y’; // ’y’ for yes, ’n’ for no; initialized to yes
cout << "Enter scores for the first student? (y/n) " << endl;
while ((cin >> reply) && (reply == ’y’ || reply == ’Y’))
{
sum_of_scores = 0; // Reset the accumulator to zero
j = 1; // Reset the assignment counter to 1
if (score < 0)
break ;
sum_of_scores += score;
j++;
}
cout << "The average score = " << sum_of_scores/NUM_ASSIGNMENTS << endl;
cout << "Enter scores for another student? (y/n) " ;
}
return 0;
} // Question: What is the output with the input: 4, 5, -6, 7, 8?
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.35
Example: Ignore Negative Inputs with continue
#include <iostream> /* File: [Link] */
using namespace std;
int main()
{
int NUM_ASSIGNMENTS = 5; // Uppercase variable doesn’t change
int j; // Assignment counter
int score, sum_of_scores;
char reply = ’y’; // ’y’ for yes, ’n’ for no; initialized to yes
cout << "Enter scores for the first student? (y/n) " << endl;
while ((cin >> reply) && (reply == ’y’ || reply == ’Y’))
{
sum_of_scores = 0; // Reset the accumulator to zero
j = 1; // Reset the assignment counter to 1
if (score < 0)
continue ;
sum_of_scores += score;
j++;
}
cout << "The average score = " << sum_of_scores/NUM_ASSIGNMENTS << endl;
cout << "Enter scores for another student? (y/n) " ;
}
return 0;
} // Question: What is the output with the input: 4, 5, -6, 7, 8 ?
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.36
Example: Difference between break and continue
if (j == 1) if (j == 1)
break; continue ;
cout << "Leave iteration " cout << "Leave iteration "
<< j << endl; << j << endl;
j++; j++;
} }
return 0; return 0;
} }
int main()
{
for (int j = 1; j <= 10; j++)
{
cout << "j = " << j << endl;
if (j == 3)
{
j = 10;
continue; // What if it is replaced by break;
}
}
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.38
Part IV
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.39
switch Statement
switch statement is a variant of the if-else-if statement, that allows
multiple choices based on the value of an integral expression.
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.40
Example: switch on Integers
#include <iostream> /* File: [Link] */
using namespace std;
switch (section)
{
case 1:
cout << "Sergey Brin" << endl; break;
case 2:
cout << "Bill Gates" << endl; break;
case 3:
cout << "Steve Jobs" << endl; break;
case 4:
cout << "Jeff Bezos" << endl; break;
default:
cerr << "Error: Invalid lecture section " << section << endl;
break;
}
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.41
Example: switch on Characters
#include <iostream> /* File: [Link] */
using namespace std;
switch (bloodtype)
{
case ’A’:
cout << "Your donor must be of blood type: O or A\n";
break;
case ’B’:
cout << "Your donor must be of blood type: O or B\n";
break;
case ’C’:
cout << "Your donor must be of blood type: O, A, B, or AB\n";
break;
case ’O’:
cout << "Your donor must be of blood type: O";
break;
default: // To catch errors
cerr << "Error: " << bloodtype << " is not a valid blood type!\n";
break;
}
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.42
Example: switch with Sharing Cases
#include <iostream> /* File: [Link] */
using namespace std;
int main() // To determine your grade (fictitious)
{
char grade; // Letter grade
int mark; // Numerical mark between 0 and 100
cin >> mark;
switch (mark/10)
{
case 10: // Several cases may share the same action
case 9:
grade = ’A’; break; // If mark >= 90
case 8: case 7: case 6: // May write several cases on 1 line
grade = ’B’; break; // If 90 > mark >= 60
case 5:
case 4:
case 3:
case 2:
grade = ’C’; break; // If 60 > mark >= 20
case 1:
grade = ’D’; break; // If 20 > mark >= 10
default:
grade = ’F’; break;
}
cout << "Your letter grade is " << grade << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.43
Example: switch vs. if-else-if
cout << "Your letter grade is " << grade << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.44
Remarks on switch
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.45
Example: Give me a break
#include <iostream> /* File: [Link] */
using namespace std;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.46
New Data Types with enum
Example
enum weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY, SUNDAY }; // 0,1,2,3,4,5,6
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.47
User-defined enum Type
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.48
Example: enum with switch
#include <iostream> /* File: [Link] */
using namespace std;
int main()
{
enum shapes { TEXT, LINE, RECT, CIRCLE };
cout << "supported shapes: "
<< " TEXT = " << TEXT << " LINE = " << LINE
<< " RECT = " << RECT << " CIRCLE = " << CIRCLE << endl;
int myshape; // Why the type of myshape is not shape?
cin >> myshape;
switch (myshape)
{
case TEXT:
cout << "Call a function to print text" << endl; break;
case LINE:
cout << "Call a function to draw a line" << endl; break;
case RECT:
cout << "Call a function to draw a rectangle" << endl; break;
case CIRCLE:
cout << "Call a function to draw a circle" << endl; break;
default:
cerr << "Error: Unsupported shape" << endl; break;
}
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.49
Part V
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.50
Quiz: Logical Operations
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.51
do-while Loop (Statement)
Syntax: do-while Statement
do { <stmts> } while (<bool-exp>);
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.52
Example: Factorial using do-while Loop
#include <iostream> /* File: [Link] */
using namespace std; // Compute x! = x(x-1)(x-2)...1; x is non -ve
int main()
{
int factorial = 1, number;
cout << "Enter a non-negative integer: ";
cin >> number;
if (number > 0)
{
do
{
factorial *= number; // Same as: factorial = factorial*number
--number; // Same as: number = number-1
} while (number > 1);
}
int sum;
Case 1: while (cin >> x)
sum += x;
int j;
while (j < 10)
{
Case 2:
cout << "hello again!" << endl;
j++;
}
int j = 0;
while (j < 10);
{
Case 3:
cout << "hello again!" << endl;
j++;
}
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.55
More enum Example: Mixing Colors
#include <iostream> /* File: [Link] */
using namespace std;
int main()
{ // Declare color variables immediately after the enum definition
enum color { RED, GREEN, BLUE, YELLOW, CYAN, PURPLE } x, y;
int xint, yint; // Input variables for the color variables
else
cerr << "Error: only support mixing RED/GREEN/BLUE!" << endl;
return 0;
} // Check what is really printed out
{ kccecia, mak, dipapado, psander, charlesz }@[Link] COMP2011 (Fall 2022) p.56