0% found this document useful (0 votes)
12 views72 pages

Chapter 5

Uploaded by

maryam osama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views72 pages

Chapter 5

Uploaded by

maryam osama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Introduction to Computer Programming (CSCI 112)

Chapter 5
Control Statements: Part 2

Dr. Ali Alnoman


Spring 2023

Reference: C++ How to Program, 10th edition, P. Deitel and H. Deitel


2

Objectives
• To use for and do…while looping statements
• To implement the switch selection statement
• How break and continue alter the flow of control statements
• To use logical operators to form complex conditional expressions in control
statements
3

Essentials of Counter-Controlled Repetition

• Counter-controlled repetition requires


▫ the name of a control variable (or loop counter)
▫ the initial value of the control variable
▫ the loop-continuation condition that tests for the final value of the
control variable (i.e., whether looping should continue)
▫ the increment (or decrement) by which the control variable is modified
each time through the loop.
4

Essentials of Counter-Controlled Repetition


• The next program prints the numbers from 1 to 10. The declaration in
line 8 names the control variable (counter), declares it to be an
unsigned int, reserves space for it in memory and sets it to an initial
value of 1
5
6
7

for Repetition Statement


• The for repetition statement specifies the counter-controlled repetition details in a
single line of code
• To illustrate the for loop, let’s rewrite the previous program using for
• The initialization occurs once when the loop is encountered
• The condition is tested next and each time the body completes
• The body executes if the condition is true
• The increment occurs after the body executes
• Then, the condition is tested again
• If there is more than one statement in the body of the for, braces are required to
enclose the body of the loop
8
9

for Repetition Statement


for Statement Header Components
10
11

for Repetition Statement


• The general form of the for statement is
for (initialization; loop_Continuation_Condition; increment )
{
statements
}
• In most cases, the for statement can be represented by an equivalent while
statement, as follows:

initialization;
while ( loop_Continuation_Condition )
{
statement
increment;
}
12

for Repetition Statement


• If the initialization expression declares the control variable, the control
variable can be used only in the body of the for statement—the control
variable will be unknown outside the for statement
• This restricted use of the control variable name is known as the
variable’s scope
• The scope of a variable specifies where it can be used in a program
13

for Repetition Statement


Expressions in the for Statement’s Header are Optional
• The three expressions in the for statement header are optional (but the
two semicolon separators are required)
• If the loop_Continuation_Condition is omitted, C++ assumes that
the condition is true, thus creating an infinite loop
• One might omit the initialization expression if the control variable is
initialized earlier in the program
14

for Repetition Statement


Increment Expression Acts Like a Standalone Statement
• The increment expression in the for statement acts like a standalone
statement at the end of the for statement’s body
• The expressions
counter = counter + 1
counter += 1
++counter
counter++
are all equivalent in the increment expression (when no other code
appears there)
15

for Repetition Statement


for Statement: Notes and Observations
• The initialization, loop-continuation condition and increment
expressions of a for statement can contain arithmetic expressions
• The “increment” of a for statement can be negative, in which case it’s
really a decrement and the loop actually counts downward
• If the loop-continuation condition is initially false, the body of the for
statement is not performed
16

Examples Using the for Statement


• Vary the control variable from 1 to 100 in increments of 1
for ( unsigned int i = 1; i <= 100; ++i )

• Vary the control variable from 100 down to 0 in decrements of 1. Notice that we used
type int for the control variable in this for header. The condition does not become false
until control variable i contains -1, so the control variable must be able to store both
positive and negative numbers
for ( int i = 100; i >= 0; --i )

• Vary the control variable from 7 to 77 in steps of 7


for (unsigned int i = 7; i <= 77; i += 7 )

• Vary the control variable from 20 down to 2 in steps of -2


for (unsigned int i = 20; i >= 2; i -= 2 )
17

Examples Using the for Statement


• Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17
for (unsigned int i = 2; i <= 17; i += 3 )

• Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55
for (unsigned int i = 99; i >= 55; i -= 11 )

• The control variable accepts formulas as well:


for (j=x; j<=4*x*y; j+=y/x)
18
19
20

for Repetition Statement


for Statement UML Activity Diagram
• The for repetition statement’s UML activity diagram is similar to that of
the while statement
• The diagram makes it clear that initialization occurs once before the
loop-continuation test is evaluated the first time, and that incrementing
occurs each time through the loop after the body statement executes
21
22

Example 1
Summing Even Integers from 2 to 20
23

for Repetition Statement


Comma-Separated Lists of Expressions
• The commas, as used in these expressions, are comma operators, which
guarantee that lists of expressions evaluate from left to right
• Although the for statement here is correct, it is more complicated (not
recommended). See the example below:
24

for Repetition Statement


#include <iostream>

int main()
{
unsigned int sum = 0; // initialize sum

for (unsigned int number = 2; number <= 10; sum += number, number += 2)
; // empty statement

cout << "Sum is " << sum << endl; // output sum
}
25

Example 2
Write a program to calculate the values of a as shown in the formula:
a =(0.8) p

Use the for loop and vary the value of p from 1 to 10


26

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{ double a;
cout << fixed << setprecision( 2 );
cout << setw( 4 ) << "p" << setw( 21 ) << "a\n" << endl;

for ( int p = 1; p <= 10; ++p )


{
a = pow( 0.8 , p );
cout << setw( 4 ) << p << setw( 21 ) << a << endl;

} // end for

}
27

CMATH header file


• C++ does not include an exponentiation operator, so we use the
standard library function pow
▫ pow(x, y) calculates the value of x raised to the yth power
▫ Takes two arguments of type double and returns a double value

• This program will not compile without including header file <cmath>
28

setw() Statement
Using Stream Manipulators to Format Numeric Output
• Parameterized stream manipulators setprecision and setw and the nonparameterized
stream manipulator fixed
• The stream manipulator setw(4) specifies that the next value output should appear in
a field width of 4—i.e., cout prints the value with at least 4 character positions
▫ If less than 4 character positions wide, the value is right justified in the field by default
• To indicate that values should be output left justified, simply output nonparameterized
stream manipulator << left <<
• Right justification can be restored by outputting nonparameterized stream manipulator
<< right <<
29

setprecision Statement
• Stream manipulator fixed indicates that floating-point values should be
output as fixed-point values with decimal points
• Stream manipulator setprecision specifies the number of digits to
the right of the decimal point
• Stream manipulators fixed and setprecision remain in effect until
they’re changed—such settings are called sticky settings
• The field width specified with setw applies only to the next value output
30

for vs while
What is the output of the code on the left? Re-write the code using the
for statement to show the same result.
Using FOR statement:
#include <iostream>
using namespace std; #include <iostream>
int main () using namespace std;
{ int main ()
int k, sum; {
sum = k = 0; OUTPUT: 5 10 int k, sum;
while (k < 5) { sum = 0;
sum += k; for (k=0; k < 5;k++) {
++k; sum += k;
} }
cout << k << " " << sum << endl; cout << k << " "<< sum << endl;
} }
31

do…while Repetition Statement


• Similar to the while statement
• The do…while statement tests the loop-continuation condition after
the loop body executes; therefore, the loop body always executes at
least once
• The following program uses a do…while statement to print the numbers
1 to 10
32
33

do…while Repetition Statement


do…while Statement UML Activity Diagram

• The following figure contains the do…while statement’s UML activity


diagram, which makes it clear that the loop-continuation condition is not
evaluated until after the loop performs its body at least once
34
35

do…while Repetition Statement


Braces in a do…while Statement
• It’s not necessary to use braces in the do…while statement if there’s only
one statement in the body; however, most programmers include the
braces to avoid confusion between the while and do…while statements
• If there are more than one statement, it is important to add the braces
36

do…while Repetition Statement


• A do…while with no braces around the single statement body
appears as
do
statement
while ( condition );

which can be confusing!


• You might misinterpret the last line—while( condition );—as a
while statement containing as its body an empty statement
37

do…while Repetition Statement


• Thus, the do…while with one statement often is written as follows to
avoid confusion:
do
{
statement
} while ( condition );
38

switch Multiple-Selection Statement


• The switch multiple-selection statement performs many different
actions based on the possible values of a variable or expression
• The switch statement consists of a series of case labels and an optional
default case
• When the flow of control reaches the switch, the program evaluates the
expression in the parentheses
▫ The controlling expression
39

switch Multiple-Selection Statement


switch Statement Details
• The switch statement compares the value of the controlling expression
with each case label
• If a match occurs, the program executes the statements for that case
• The break statement causes program control to proceed with the first
statement after the switch
40

switch Multiple-Selection Statement


• 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
41

Exercise: Use the switch statement to count how many times a user
entered the letters ‘A’ and ‘B’

#include <iostream>
using namespace std;

int main()
{
int grade; // one grade
unsigned int aCount = 0; // number of As
unsigned int bCount = 0; // number of Bs
cout << "Enter the letter grades" << endl;
cout << "Enter the EOF character to end input" << endl;
42

// loop until user types end-of-file key case '\n': // ignore newlines,
sequence case '\t': // tabs
while ( ( grade = cin.get() ) != EOF ) { case ' ': // and spaces in input
switch ( grade ) { break; // exit switch
case 'A': // grade was uppercase A
case 'a': // or lowercase a default: // catch all other characters
++aCount; // increment aCount cout << "Incorrect letter grade
break; // necessary to exit switch entered." <<endl ;
cout << " Enter a new grade." << endl;
case 'B': // grade was uppercase B break;
case 'b': // or lowercase b } // end switch
++bCount; // increment bCount } // end while
break; // exit switch
43

// output summary of results


cout << "Totals for each letter grade are:" << endl;
cout << "A: " << aCount << endl; // display number of A grades
cout << "B: " << bCount << endl; // display number of B grades

} // end function main

EOF means End of File:


EOF key in windows CTRL+z ,then, press ENTER
in MAC CTRL+d
44

switch Multiple-Selection Statement


Reading Character Input
• The cin.get() function reads one character from the keyboard
• Normally, characters are stored in variables of type char; however, characters can be
stored in any integer data type, because types short, int , long and long long are
guaranteed to be at least as big as type char
• For example, the statement
cout << "The character (" << 'a' << ") has the value “ << static_cast< int > (
'a' ) << endl;

• prints the character a and its integer value as follows:


The character (a) has the value 97

• The integer 97 is the character’s numerical representation in the computer


45

switch Multiple-Selection Statement


• EOF stands for “end-of-file”. Commonly used as a sentinel value
▫ However, you do not type the value –1, nor do you type the letters EOF as the sentinel
value
▫ You type a system-dependent keystroke combination that means “end-of-file” to
indicate that you have no more data to enter

• EOF is a symbolic integer constant defined in the <iostream> header file


46
47

switch Multiple-Selection Statement


Providing a default Case
• If no match occurs between the controlling expression’s value and a case
label, the default case executes
• 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
48

switch Multiple-Selection Statement


Ignoring Newline, Tab and Blank Characters in Input
• Reading characters one at a time can cause some 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
49

switch Multiple-Selection Statement


switch Statement UML Activity Diagram
• The following figure shows the UML of switch statement
• Most switch statements use a break in each case to terminate the switch
statement after processing the case
• 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
50
51

Notes on Data Types


Notes on Data Types
• C++ has flexible data type sizes
• C++ provides several integer types
• The range of integer values for each type is platform dependent (e.g. 32-bit. 64-bit systems)
• In addition to the types int and char, C++ provides the types short (an abbreviation of
short int),long (an abbreviation of long int) and long long (an abbreviation of long
long int)
• The minimum range of values for short integers is –32,767 to 32,767
• For the vast majority of integer calculations, long integers are sufficient
• The minimum range of values for long integers is –2,147,483,648 to 2,147,483,647
52

Notes on Data Types


• On most computers, int is equivalent either to short or to long
• The range of values for an int is at least the same as that for short
integers and no larger than that for long integers
• The data type char can be used to represent any of the characters in
the computer’s character set
53

break and continue Statements


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
• The following program demonstrates the break statement to exit a for
repetition statement
54

break Statement: Exercise


#include <iostream>
using namespace std;
int main()
{
unsigned int x; // counter
for ( x = 1; x <= 10; ++x ) {

if ( x == 5 ) {
break; // break loop only if x is 5 The code prints the
} // end if numbers from 1 to 4
cout << x << endl; // display value of x
because the break
} // end for statement exits the
cout << "Broke out of loop at x = " << x << endl; loop when x equals 5
} // end function main
55

break and continue Statements


• 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
• The following program demonstrates the continue statement to exit a
for repetition statement
56

continue Statement: Exercise


#include <iostream>
using namespace std;
int main()
{
unsigned int x; // counter
for ( x = 1; x <= 10; ++x ) {

if ( x == 5 ) {
continue; // break loop only if x is 5
} // end if The code prints the
numbers from 1 to 10
cout << x << endl; // display value of x
} // end for
but skips printing the
cout << “Number 5 is skipped" << endl; number 5
} // end function main
57

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)
58

Logical Operators
Logical AND (&&) Operator
• The && (logical AND) operator is used to ensure that two conditions are both true
before we choose a certain path of execution
• The simple condition to the left of the && operator evaluates first
• The simple condition to the right of the && operator evaluates next
• The right side of a logical AND expression is evaluated only if the left side is true

if ( gender == 1 && age >= 18 )


i++;
59

Logical AND (&&) Operator: truth table


60

Logical Operators
Logical OR (||) Operator
• The || (logical OR) operator determines if either or both of two conditions are true
before we choose a certain path of execution
• The && operator has a higher precedence than the || operator
• Both operators associate from left to right

if ( semesterAverage >= 90 || finalExam >= 90 )


cout<< "Student grade is A“ << endl;
61

Logical OR (||) Operator: truth table


62

Logical Operators
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
• You can often avoid the ! operator by using an appropriate relational or equality
operator
if ( !( grade == sentinelValue ) )
cout << "The next grade is “ << grade << endl; OR ..
if ( grade != sentinelValue )
cout << "The next grade is “ << grade << endl;
63

Logical Negation (!) Operator: truth table


64

Logical Operators
Logical Operators Example
• The following program demonstrates the logical operators by producing
their truth tables
• The output shows each expression that is evaluated and its bool result
• By default, bool values true and false are displayed by cout and the
stream insertion operator as 1 and 0, respectively
• Stream manipulator boolalpha (a sticky manipulator) specifies that the
value of each bool expression should be displayed as either the word
“true” or the word “false”
65
66
Exercises
68

Exercise 1
Write a program that uses for statement to print the following shape.

*
** #include <iostream>
*** using namespace std;
****
***** int main()
{
for (int i=1;i<=5;i++)
{
for (int j=1;j<=i;j++)
{cout << "*";}

cout << endl;


} // outer for loop
} // end main
69

Exercise 2
What is the output?
#include <iostream>
using namespace std;
int main ()
{ for ( int i = 1; i <= 5; ++i )
{
for ( int j = 1; j <= 3; ++j )
{
for ( int k = 1; k <= 4; ++k )
cout << '*';
cout << endl;
} // end inner for
cout << endl;
} // end outer for
}
70

Exercise 3
What is the output? for ( int i = 1; i <= y; ++i ) // count from 1 to y
{
for ( int j = 1; j <= x; ++j )
#include <iostream>
cout << '@'; // output @
using namespace std;

cout << endl; // begin new line


int main()
} // end outer for
{
} // end main
int x; // declare x
int y; // declare y

// prompt user for input OUTPUT:


cout << "Enter two integers in the range 1-20: "; Enter two integers in the range 1-20:
3
cin >> x >> y; // read values for x and y
2
@@@
@@@
71

Exercise 4
Find the error(s), if any, in each of the following: c) The following code should output the odd integers from 19
a) for ( x = 100, x >= 1, ++x ) to 1:
cout << x << endl; for ( x = 19; x >= 1; x += 2 )
cout << x << endl;

b) The following code should print whether integer value is


odd or even: d) The following code should output the even integers from 2
switch ( value % 2 ) to 100:
{ counter = 2;
case 0: do
cout << "Even integer" << endl; {
case 1: cout << counter << endl;
cout << "Odd integer" << endl; counter += 2;
} } While ( counter < 100 );
72

Exercise 5
Write a program that uses a for statement to calculate and print the sum of the odd
integers from 1 to 6

#include <iostream>
using namespace std;
int main()
{
int sum=0; OUTPUT:
for (int i=1; i<=6; i++) 9
{ Now, write another
if ( (i % 2) != 0) program to calculate and
{sum = sum + i ;}
} print the product of odd
cout << "The sum of odd numbers is " << sum << endl; numbers from 1 to 6
} // end main In this case the result
should be 15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy