SlideShare a Scribd company logo
1 of 61
An Introduction To Software
Development Using C++
Class #13:
Char, Switch, Break,
Continue,
Logical Operators
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
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
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
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
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
GradeBook Class with switch Statement
to Count A, B, C, D and F Grades
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
ASCII Codes
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
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
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
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.
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
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.
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
switch Statement
UML Activity Diagram
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.
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
Software Engineering Tips!
• Specifying a nonconstant integral expression in a switch’s
case label is a syntax error.
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
Program demonstrates the break statement
exiting a for repetition statement.
2
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
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
continue statement terminating an
iteration of a for statement
3
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
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.
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
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
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 )
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++.
&& (logical AND) operator
truth table
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
Logical OR (||) Operator
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
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.
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
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
Logical Negation (!) Operator
Logical Operators Example
4
Operator Precedence and
Associativity
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
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
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.
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
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
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.
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
C++’s single-entry/single-exit sequence,
selection and repetition statements.
• 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
Rules For Forming
Structured Programs
Simplest activity diagram
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
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/
What’s In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline While
For do…While Break /
Continue
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/
An Introduction To Software
Development Using C++
Class #3:
Variables, Math
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
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
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/
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/

More Related Content

What's hot

Learn C
Learn CLearn C
Learn Ckantila
 
Programming concepts By ZAK
Programming concepts By ZAKProgramming concepts By ZAK
Programming concepts By ZAKTabsheer Hasan
 
08 subprograms
08 subprograms08 subprograms
08 subprogramsbaran19901990
 
Field symbols
Field symbolsField symbols
Field symbolsskumar_sap
 
Precedence and associativity (Computer programming and utilization)
Precedence and associativity (Computer programming and utilization)Precedence and associativity (Computer programming and utilization)
Precedence and associativity (Computer programming and utilization)Digvijaysinh Gohil
 
problem solving and design By ZAK
problem solving and design By ZAKproblem solving and design By ZAK
problem solving and design By ZAKTabsheer Hasan
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Iffat Anjum
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityAakash Singh
 
Programing techniques
Programing techniquesPrograming techniques
Programing techniquesPrabhjit Singh
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput Ahmad Idrees
 
Type conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingType conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingDhrumil Panchal
 
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHMCLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHMRc Os
 
Algorithm - Introduction
Algorithm - IntroductionAlgorithm - Introduction
Algorithm - IntroductionMadhu Bala
 

What's hot (20)

Learn C
Learn CLearn C
Learn C
 
Ch03
Ch03Ch03
Ch03
 
Programming concepts By ZAK
Programming concepts By ZAKProgramming concepts By ZAK
Programming concepts By ZAK
 
Fieldsymbols
FieldsymbolsFieldsymbols
Fieldsymbols
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Field symbols
Field symbolsField symbols
Field symbols
 
Precedence and associativity (Computer programming and utilization)
Precedence and associativity (Computer programming and utilization)Precedence and associativity (Computer programming and utilization)
Precedence and associativity (Computer programming and utilization)
 
problem solving and design By ZAK
problem solving and design By ZAKproblem solving and design By ZAK
problem solving and design By ZAK
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Programing techniques
Programing techniquesPrograming techniques
Programing techniques
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Modular programming
Modular programmingModular programming
Modular programming
 
Ch04
Ch04Ch04
Ch04
 
Type conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingType conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programming
 
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHMCLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
 
Algorithm - Introduction
Algorithm - IntroductionAlgorithm - Introduction
Algorithm - Introduction
 
10. sub program
10. sub program10. sub program
10. sub program
 
Programming in c by pkv
Programming in c by pkvProgramming in c by pkv
Programming in c by pkv
 

Similar to C++ Software Development Class: Char, Switch, Break

Intro To C++ - Cass 11 - Converting between types, formatting floating point,...
Intro To C++ - Cass 11 - Converting between types, formatting floating point,...Intro To C++ - Cass 11 - Converting between types, formatting floating point,...
Intro To C++ - Cass 11 - Converting between types, formatting floating point,...Blue Elephant Consulting
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
2nd PUC Computer science chapter 5 review of c++
2nd PUC Computer science chapter 5   review of c++2nd PUC Computer science chapter 5   review of c++
2nd PUC Computer science chapter 5 review of c++Aahwini Esware gowda
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variablesTony Apreku
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programmingNgeam Soly
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants Hemantha Kulathilake
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx20EUEE018DEEPAKM
 
0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdfssusere19c741
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
C programming language
C programming languageC programming language
C programming languageAbin Rimal
 
Control structure
Control structureControl structure
Control structureSamsil Arefin
 
Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Dhiviya Rose
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plusRalph Weber
 

Similar to C++ Software Development Class: Char, Switch, Break (20)

Intro To C++ - Cass 11 - Converting between types, formatting floating point,...
Intro To C++ - Cass 11 - Converting between types, formatting floating point,...Intro To C++ - Cass 11 - Converting between types, formatting floating point,...
Intro To C++ - Cass 11 - Converting between types, formatting floating point,...
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
2nd PUC Computer science chapter 5 review of c++
2nd PUC Computer science chapter 5   review of c++2nd PUC Computer science chapter 5   review of c++
2nd PUC Computer science chapter 5 review of c++
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programming
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
C programming
C programmingC programming
C programming
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
C programming language
C programming languageC programming language
C programming language
 
Control structure
Control structureControl structure
Control structure
 
Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2Programming for Problem Solving Unit 2
Programming for Problem Solving Unit 2
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
C basics
C basicsC basics
C basics
 
C basics
C basicsC basics
C basics
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

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
  • 7. GradeBook Class with switch Statement to Count A, B, C, D and F Grades
  • 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
  • 22. Program demonstrates the break statement exiting a for repetition statement. 2
  • 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
  • 25. continue statement terminating an iteration of a for statement 3
  • 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++.
  • 32. && (logical AND) operator truth table
  • 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
  • 34. Logical OR (||) Operator
  • 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

  1. 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.
  2. 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.