This presentation is a part of the COP2272C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce students to the C++ language and the fundamentals of object orientated programming..
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
C++ Software Development Class: Char, Switch, Break
1. An Introduction To Software
Development Using C++
Class #13:
Char, Switch, Break,
Continue,
Logical Operators
2. One More Data Type: Char
⢠Character types: They can represent a single character, such as 'A' or '$'. The most
basic type is char, which is a one-byte character
⢠Note that when assigning a value to a char variable, you need to use single quotes:
x = 'a';
⢠It now becomes easy to switch between characters and numbers:
char x,y;
x = 97;
y = âb';
cout << static_cast<char>(x) << endl;
cout << static_cast<int>(y) << endl;
Results in:
a
98
Image Credit: www.activityvillage.co.uk
3. Quick In Class Programming
Challenge: Encode SS #
⢠Given the Social Security #: 123-45-6789
⢠Encode it by changing each number into an alphabetic
character. The ASCII code for a â1â is 49 and the ASCII code for
an âaâ is 97.
⢠Tell me what the final encoded string is.
⢠Notes:
â static_cast<> is how C++ converts between types
â We just learned about the char variable type â use it!
Image Credit: www.nyc.gov
4. switch Multiple-Selection
Statement
⢠C++ provides the switch multiple-selection statement
to perform many different actions based on the
possible values of a variable or expression.
⢠Each action is associated with the value of a constant
integral expression (i.e., any combination of
character and integer constants that evaluates to a
constant integer value).
Image Credit: www.bhamrail.com
5. GradeBook Class with switch Statement
to Count A, B, C, D and F Grades
⢠This next version of the GradeBook class asks the user to enter a set of letter
grades, then displays a summary of the number of students who received each
grade.
⢠The class uses a switch to determine whether each grade entered is an A, B, C, D
or F and to increment the appropriate grade counter.
⢠Like earlier versions of the class definition, the GradeBook class definition contains
function prototypes for member functions setCourseName, getCourseName and
displayMessage, as well as the classâs constructor.
⢠The class definition also declares private
data member courseName.
Image Credit: www.alcoteachersfcu.org1
6. GradeBook Class with switch Statement
to Count A, B, C, D and F Grades
⢠Class GradeBook now contains five additional private data members â counter
variables for each grade category (i.e., A, B, C, D and F).
⢠The class also contains two additional public member functionsâinputGrades and
displayGradeReport.
⢠Member function inputGrades reads an arbitrary number of letter grades from the
user using sentinel-controlled repetition and updates the appropriate
grade counter for each grade entered.
⢠Member function displayGradeReport outputs a
report containing the number of students who received
each letter grade.
Image Credit: www.law.lsu.edu
8. Reading Character Input
⢠The user enters letter grades for a course in member function inputGrades.
⢠In the while header the parenthesized assignment (grade = cin.get()) executes
first.
⢠The cin.get() function reads one character from the keyboard and stores that
character in integer variable grade.
⢠Normally, characters are stored in variables of type char; however, characters can
be stored in any integer data type, because types short, int and long are
guaranteed to be at least as big as type char.
⢠Thus, we can treat a character either as an integer or as a character, depending on
its use. For example, the statement
prints the character a and its integer value as follows:
cout << "The character (" << 'a' << ") has the value "
<< static_cast< int > ( 'a' ) << endl;
The character (a) has the value 97
Image Credit: phillyvirtual.com
10. Reading Character Input
⢠Generally, assignment statements have the value thatâs assigned to the variable on
the left side of the =. Thus, the value of the assignment expression
grade = cin.get() is the same as the value returned by cin.get() and assigned to the
variable grade.
⢠The fact that assignment expressions have values can be useful
for assigning the same value to several variables. For example:
⢠first evaluates c = 0 (because the = operator associates from right to left). The
variable b is then assigned the value of c = 0 (which is 0). Then, a is assigned the
value of b = (c = 0) (which is also 0).
⢠In the program, the value of grade = cin.get() is compared with the value of EOF
(a symbol whose acronym stands for âend-of-fileâ).
⢠In this program, the user enters grades at the keyboard. When the user presses the
Enter key, the characters are read by the cin.get() function, one character at a
time. If the character entered is not end-of-file, the flow of control enters the
switch statement, which increments the appropriate letter-grade counter.
a = b = c = 0;
Image Credit: www.ocps.net
11. switch Statement Details
⢠The switch statement consists of a series of case labels and an optional
default case.
⢠These are used in this example to determine which counter to increment, based
on a grade.
⢠When the flow of control reaches the switch, the program evaluates the
expression in the parentheses (i.e., grade) following keyword switch.
This is called the controlling expression.
⢠The switch statement compares the value of the controlling expression with
each case label.
⢠Assume the user enters the letter C as a grade. The program compares C to
each case in the switch. If a match occurs, the program executes the statements
for that case. For the letter C, the program increments cCount by 1. The break
statement causes program control to proceed with the first statement after the
switch Image Credit: www.eldontaylor.com
12. switch Statement Details
⢠The cases in our switch explicitly test for the lowercase
and uppercase versions of the letters A, B, C, D and F.
⢠Note the cases that test for the values 'A' and 'aâ
(both of which represent the grade A).
⢠Listing cases consecutively with no statements between them enables the cases to
perform the same set of statementsâwhen the controlling expression evaluates to
either 'A' or 'a', the associated statements will execute.
⢠Each case can have multiple statements. The switch selection statement does not
require braces around multiple statements in each case.
⢠Without break statements, each time a match occurs in the switch, the statements
for that case and subsequent cases execute until a break statement or the end of
the switch is encountered.
Image Credit: www.joytime.org
13. Software Engineering Tips!
⢠Forgetting a break statement when one is needed in a switch
statement is a logic error.
⢠Omitting the space between the word case and the integral
value tested in a switch statementâe.g., writing case3:
instead of case 3:âis a logic error. The switch statement
will not perform the appropriate actions when the controlling
expression has a value of 3.
14. Providing a default Case
⢠If no match occurs between the controlling expressionâs value and a case label, the
default case executes.
⢠We use the default case in this example to process all controlling-expression
values that are neither valid grades nor newline, tab or space characters.
⢠If no match occurs, the default case executes, and the program prints an error
message indicating that an incorrect letter grade was entered.
⢠If no match occurs in a switch statement that does not contain a default case,
program control continues with the first statement after the switch.
Image Credit: devblackops.io
15. Software Engineering Tips!
⢠Provide a default case in switch statements. Cases not
explicitly tested in a switch statement without a default case
are ignored. Including a default case focuses you on the
need to process exceptional conditions. There are situations
in which no default processing is needed. Although the case
clauses and the default case clause in a switch statement can
occur in any order, itâs common practice to place the default
clause last.
⢠The last case in a switch statement does not require a break
statement. Some programmers include this break for clarity
and for symmetry with other cases.
16. Ignoring Newline, Tab and Blank
Characters in Input
⢠Parts of the program in the switch statement cause the program to skip newline,
tab and blank characters.
⢠Reading characters one at a time can cause problems.
⢠To have the program read the characters, we must send them to the computer by
pressing the Enter key.
⢠This places a newline character in the input after the character we wish to process.
⢠Often, this newline character must be specially processed. By including these cases
in our switch statement, we prevent the error message in the default case from
being printed each time a newline, tab or space is encountered in the input.
Image Credit: www.theacornwithin.com
18. switch Statement
UML Activity Diagram
⢠Most switch statements use a break in each case to terminate the switch
statement after processing the case.
⢠This UML diagram emphasizes this by including break statements in the activity
diagram. Without the break statement, control would not transfer to the first
statement after the switch statement after a case is processed. Instead, control
would transfer to the next caseâs actions.
⢠The diagram makes it clear that the break statement at the end of a case causes
control to exit the switch statement immediately. Again, note that (besides an
initial state, transition arrows, a final state and several notes) the diagram contains
action states and decisions. Also, the diagram uses merge symbols to merge the
transitions from the break statements to the final state.
19. switch Statement
UML Activity Diagram
⢠When using the switch statement, remember that each case can be used to test
only a constant integral expressionâany combination of character constants and
integer constants that evaluates to a constant integer value.
⢠A character constant is represented as the specific character in single quotes, such
as 'A'. An integer constant is simply an integer value. Also, each case label can
specify only one constant integral expression.
Image Credit: www.joytime.org
20. Software Engineering Tips!
⢠Specifying a nonconstant integral expression in a switchâs
case label is a syntax error.
21. break Statement
⢠The break statement, when executed in a while, for, doâŚwhile or switch
statement, causes immediate exit from that statement.
⢠Program execution continues with the next statement.
⢠Common uses of the break statement are to escape early from a loop or to skip
the remainder of a switch statement.
Image Credit: hisamazinggloryministries.org
23. Program demonstrates the break statement
exiting a for repetition statement.
⢠When the if statement detects that count is 5, the break statement executes.
⢠This terminates the for statement, and the program proceeds to immediately after
the for statement, which displays a message indicating the control variable value
that terminated the loop.
⢠The for statement fully executes its body only four times instead of 10.
⢠The control variable count is defined outside the for statement header, so that we
can use the control variable both in the loopâs body and after the loop completes
its execution.
Image Credit: twitter.com
24. continue Statement
⢠The continue statement, when executed in a while, for or doâŚwhile statement,
skips the remaining statements in the body of that statement and proceeds with
the next iteration of the loop.
⢠In while and doâŚwhile statements, the loop-continuation test evaluates
immediately after the continue statement executes. In the for statement, the
increment expression executes, then the loop-continuation test evaluates.
Image Creditgorselbilgi.com
26. continue statement terminating an
iteration of a for statement
⢠In this program, we use the continue statement in a for statement to skip the
output statement when the nested if determines that the value of count is 5.
⢠When the continue statement executes, program control continues with the
increment of the control variable in the for header and loops five more times.
Image Credit: energyzarr.typepad.com
27. Software Engineering Tips!
⢠Thereâs a tension between achieving quality software
engineering and achieving the best performing software.
Often, one of these goals is achieved at the expense of the
other. For all but the most performance-intensive situations,
apply the following guidelines: First, make your code simple
and correct; then make it fast and small, but only if necessary.
⢠Some programmers feel that break and continue violate
structured programming. The effects of these statements can
be achieved by structured programming techniques we soon
will learn, so these programmers do not use break and
continue. Most programmers consider the use of break in
switch statements acceptable.
28. Logical Operators
⢠C++ provides logical operators that are used to form more complex conditions by
combining simple conditions.
⢠The logical operators are && (logical AND), || (logical OR) and ! (logical NOT, also
called logical negation).
Image Credit: mncriticalthinking.com
29. Logical AND (&&) Operator
⢠Suppose that we wish to ensure that two conditions are both true before we
choose a certain path of execution. In this case, we can use the && (logical AND)
operator, as follows:
⢠This if statement contains two simple conditions. The condition gender == 1 is
used here to determine whether a person is a female. The condition age >= 65
determines whether a person is a senior citizen. The simple condition to the left of
the && operator evaluates first. If necessary, the simple condition to the right of
the && operator evaluates next.
⢠As weâll discuss shortly, the right side of a logical
AND expression is evaluated only if the left side is true.
if ( gender == 1 && age >= 65 )
++seniorFemales;
Image Credit: mncriticalthinking.com
30. Logical AND (&&) Operator
⢠The if statement then considers the combined condition:
This condition is true if and only if both of the simple conditions are true.
⢠Finally, if this combined condition is indeed true, the statement in the if
statementâs body increments the count of seniorFemales.
⢠If either (or both) of the simple conditions are false, then the program skips the
incrementing and proceeds to the statement following the if.
⢠The preceding combined condition can be made more readable
by adding redundant parentheses:
gender == 1 && age >= 65
( gender == 1 ) && ( age >= 65 )
31. Software Engineering Tips!
⢠Although 3 < x < 7 is a mathematically correct condition, it
does not evaluate as you might expect in C++.
Use ( 3 < x && x < 7 ) to get the proper evaluation in C++.
33. Logical OR (||) Operator
⢠Now letâs consider the || (logical OR) operator.
⢠Suppose we wish to ensure that either or both of two conditions are true before
we choose a certain path of execution. In this case, we use the || operator, as in
the following program segment:
⢠This preceding condition contains two simple conditions. The simple condition
semesterAverage >= 90 evaluates to determine whether the student deserves an
âAâ in the course because of a solid performance throughout the semester. The
simple condition finalExam >= 90 evaluates to determine whether the student
deserves an âAâ in the course because of an outstanding performance on the final
exam.
⢠The if statement then considers the combined condition and awards the student
an âAâ if either or both of the simple conditions are true. The message âStudent
grade is Aâ prints unless both of the simple conditions are false.
if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) )
cout << "Student grade is A" << endl;
Image Credit: www.playbuzz.com
35. Logical OR (||) Operator
⢠The && operator has a higher precedence than the || operator.
⢠Both operators associate from left to right.
⢠An expression containing && or || operators evaluates only until the truth or
falsehood of the expression is known.
⢠Thus, evaluation of the expression stops immediately if gender is not equal to 1
(i.e., the entire expression is false) and continues if gender is equal to 1 (i.e., the
entire expression could still be true if the condition age >= 65 is true).
⢠This performance feature for the evaluation of logical AND and logical
OR expressions is called short-circuit evaluation.
Image Credit: www.amazon.com
36. Software Engineering Tips!
⢠In expressions using operator &&, if the separate conditions
are independent of one another, make the condition most
likely to be false the leftmost condition. In expressions using
operator ||, make the condition most likely to be true the
leftmost condition.
This use of short-circuit evaluation can reduce a programâs
execution time.
37. Logical Negation (!) Operator
⢠C++ provides the ! (logical NOT, also called logical negation) operator to âreverseâ a
conditionâs meaning.
⢠The unary logical negation operator has only a single condition as an operand.
⢠The unary logical negation operator is placed before a condition when we are
interested in choosing a path of execution if the original condition (without the
logical negation operator) is false, such as in the following program segment:
⢠The parentheses around the condition grade == sentinelValue are
needed because the logical negation operator has a higher
precedence than the equality operator.
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Image Credit: www.ppcplans.com
38. Logical Negation (!) Operator
⢠You can often avoid the ! operator by using an appropriate relational or equality
operator. For example, the preceding if statement also can be written as follows:
⢠This flexibility often can help you express a condition in a more ânaturalâ or
convenient manner.
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;
Image Credit: www.creattor.com
42. Confusing the Equality (==) and
Assignment (=) Operators
⢠Thereâs one error that C++ programmers, no matter how experienced, tend to
make so frequently that I feel it requires a separate section.
⢠That error is accidentally swapping the operators == (equality) and = (assignment).
⢠What makes this so damaging is that it ordinarily does not cause syntax errorsâ
statements with these errors tend to compile correctly and the programs run to
completion, often generating incorrect results through runtime logic errors.
⢠Some compilers issue a warning when = is used in a context where == is expected.
Image Credit: www.ppcplans.com
43. Confusing the Equality (==) and
Assignment (=) Operators
⢠Two aspects of C++ contribute to these problems. One is that any expression that
produces a value can be used in the decision portion of any control statement.
⢠If the value of the expression is zero, itâs treated as false, and if the value is
nonzero, itâs treated as true.
⢠The second is that assignments produce a valueânamely, the value assigned to
the variable on the left side of the assignment operator.
⢠For example, suppose we intend to write:
but we accidentally write:
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
if ( payCode = 4 )
cout << "You get a bonus!" << endl;
Image Credit: jordanfel.wordpress.com
44. Software Engineering Tips!
⢠Using operator == for assignment and using operator = for
equality are logic errors.
⢠Programmers normally write conditions such as x == 7 with
the variable name on the left and the constant on the right. By
placing the constant on the left, as in 7 == x, youâll be
protected by the compiler if you accidentally replace the ==
operator with = . The compiler treats this as a compilation
error, because you canât change the value of a constant. This
will prevent the potential devastation of a runtime logic error.
45. Confusing the Equality (==) and
Assignment (=) Operators
⢠The first if statement properly awards a bonus to the person whose payCode is
equal to 4.
⢠The second oneâwith the errorâevaluates the assignment expression in the if
condition to the constant 4. Any nonzero value is interpreted as true, so this
condition is always true and the person always receives a bonus regardless of what
the actual paycode is!
⢠Even worse, the paycode has been modified when it was only supposed to be
examined!
Image Credit: educational-alternatives.net
46. Confusing the Equality (==) and
Assignment (=) Operators
⢠Thereâs another equally unpleasant situation. Suppose you
want to assign a value to a variable with a simple statement like:
but instead write
⢠This is not a syntax error. Rather, the compiler simply evaluates the conditional
expression. If x is equal to 1, the condition is true and the expression evaluates to
the value true. If x is not equal to 1, the condition is false and the expression
evaluates to the value false.
⢠Regardless of the expressionâs value, thereâs no assignment operator, so the value
simply is lost. The value of x remains unaltered, probably causing an execution-
time logic error.
⢠Sorry - there is not a handy trick available to help you with this problem!
x = 1;
x == 1;
Image Credit: paulbuckley14059.wordpress.com
47. Software Engineering Tips!
⢠Use your text editor to search for all occurrences of = in your
program and check that you have the correct assignment
operator or logical operator in each place.
48. Structured Programming Summary
⢠Weâve learned that structured programming produces programs that are easier
than unstructured programs to understand, test, debug, modify, and
even prove correct in a mathematical sense.
Image Credit: www.conductor.com
50. ⢠The previous diagram uses activity diagrams to
summarize C++âs control statements.
⢠The initial and final states indicate the single entry point
and the single exit point of each control statement.
⢠Arbitrarily connecting individual symbols in an activity diagram can lead to
unstructured programs. Therefore, the programming profession uses only a limited
set of control statements that can be combined in only two simple ways to build
structured programs.
⢠For simplicity, only single-entry/single-exit control statements are usedâthereâs
only one way to enter and only one way to exit each control statement.
⢠Connecting control statements in sequence to form structured programs is
simpleâthe final state of one control statement is connected to the initial state of
the nextâthat is, theyâre placed one after another in a program. Weâve called this
control-statement stacking.
C++âs single-entry/single-exit sequence,
selection and repetition statements.
Image Credit: www.opendoorpersonnel.com
53. Rules For Forming
Structured Programs
⢠The rules assume that action states may be used to indicate any action.
⢠The rules also assume that we begin with the so-called simplest activity diagram,
consisting of only an initial state, an action state, a final state and transition
arrows.
⢠Applying the Rules For Forming Structured Programs always results in an activity
diagram with a neat, building-block appearance.
Image Credit: www.conductor.com
54. What We Covered Today
1. We then discussed a new type of
variable: Char
2. We then discussed the Switch
statement.
3. We covered both the Break and
Continue statements.
4. Finally we wrapped things up by
reviewing Logical Operators
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
55. Whatâs In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline While
For doâŚWhile Break /
Continue
56. What Weâll Be Covering Next Time
1. Review for the
midterm!
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
57. An Introduction To Software
Development Using C++
Class #3:
Variables, Math
58. Todayâs In-Class C++
Programming Assignment
⢠A palindrome is a number or a text phrase that reads the same backwards
as forwards. For example, each of the following five-digit integers is a
palindrome: 12321, 55555, 45554 and 11611.
⢠Write a program that reads in a five-digit integer and determines whether
it is a palindrome.
⢠(Hint: Use the division and modulus operators to separate the number
into its individual digits.):
Image Credit:: tulipbyanyname.com
59. Answer To Todayâs Challenge
// File: In-Class Exercise 8 - Palindrome
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int number, firstDigit, secondDigit, fourthDigit, fifthDigit;
cout << "Enter a five-digit number: ";
cin >> number;
firstDigit = number / 10000;
secondDigit = number % 10000 / 1000;
fourthDigit = number % 10000 % 1000 % 100 / 10;
fifthDigit = number % 10000 % 1000 % 10;
if ( firstDigit == fifthDigit && secondDigit == fourthDigit )
cout << number << " is a palindrome" << endl;
else
cout << number << " is not a palindrome" << endl;
return 0;
}
Image Credit: www.lexjustis.com
60. What We Covered Today
1. We discovered what
palindromes are.
2. Created a program to
detect 5-digit
palindromes.
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
61. What Weâll Be Covering Next Time
1. Review for the
Midterm!
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
Editor's Notes
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
Iâm willing to pay you to do that.
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
Iâm willing to pay you to do that.