[go: up one dir, main page]

0% found this document useful (0 votes)
30 views80 pages

Chapter 4

This document is a chapter from an introductory computer programming course focused on control statements in C++. It covers problem-solving techniques, algorithms, and various control structures such as selection and repetition statements in C++. The chapter emphasizes the importance of understanding program control and provides examples of pseudocode and C++ implementations.

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)
30 views80 pages

Chapter 4

This document is a chapter from an introductory computer programming course focused on control statements in C++. It covers problem-solving techniques, algorithms, and various control structures such as selection and repetition statements in C++. The chapter emphasizes the importance of understanding program control and provides examples of pseudocode and C++ implementations.

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/ 80

Introduction to Computer Programming (CSCI 112)

Chapter 4
Control Statements: Part 1

Dr. Ali Alnoman


Spring 2023

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


2

Objectives
• Basic problem-solving techniques
• To develop algorithms through the process of top-down, stepwise refinement
• To use the if and if…else selection statements to choose among alternative
actions
• To use the while repetition statement to execute statements in a program
repeatedly
• Counter-controlled repetition and sentinel-controlled repetition
• To use the increment, decrement, and assignment operators
3

Introduction
• Before writing a program to solve a problem, we must have a thorough
understanding of the problem and a carefully planned approach to
solving it
• When writing a program, we must also understand the types of building
blocks that are available and employ proven program construction
techniques
4

Algorithms
• Any solvable computing problem can be solved by the execution a series
of actions in a specific order
• An algorithm is procedure for solving a problem in terms of
▫ the actions to execute, and
▫ the order in which the actions execute
• Specifying the order in which statements (actions) execute in a computer
program is called program control
• This chapter investigates program control using C++’s control statements
5

Pseudocode
• Pseudocode (or “fake” code) is an artificial and informal language that
helps to develop algorithms
• Similar to everyday English, convenient and user friendly
• Helps you “think out” a program before attempting to write it
• Carefully-prepared pseudocode can easily be converted to a
corresponding C++ program
• Normally describes only executable statements
• Declarations (that do not have initializers or do not involve constructor
calls) are not executable statements
6

Pseudocode
Below is an algorithm that inputs two integers from the user,
adds these integers and displays their sum
7

Control Structures
• Normally, statements in a program execute one after the other in the order in which
they’re written
▫ Called sequential execution
• Various C++ statements enable you to specify that the next statement to execute
may be other than the next one in sequence
▫ Called transfer of control
• All programs could be written in terms of only three control structures:
▫ the sequence structure
▫ the selection structure
▫ the repetition structure
• When we introduce C++’s implementations of control structures, we’ll refer to them
in the terminology of the C++ standard document as “control statements.”
8

Control Structures
• Unless directed otherwise, the computer executes C++ statements one
after the other in the order in which they’re written—that is, in
sequence
• The Unified Modeling Language (UML) activity diagram in the figure
below illustrates a typical sequence structure in which two calculations
are performed in order
• C++ allows us to have as many actions as we want in a sequence
structure
9
10

Control Structures
• An activity diagram models the workflow (also called the activity) of a portion of a
software system. Such workflows may include a portion of an algorithm, such as the
sequence structure in the figure above
• Activity diagrams are composed of special-purpose symbols, such as action state
symbols (a rectangle with its left and right sides replaced with arcs curving outward),
diamonds and small circles; these symbols are connected by transition arrows, which
represent the flow of the activity
• Activity diagrams help to develop and represent algorithms, but many programmers
prefer pseudocode
• Activity diagrams clearly show how control structures operate
• Action states represent actions to perform
▫ Each contains an action expression that specifies a particular action to perform
11

Control Structures
• The arrows in the activity diagram are called transition arrows
• The solid circle at the top of the diagram represents the activity’s initial-
state—the beginning of the workflow before the program performs the
modeled activities
• The solid circle surrounded by a hollow circle that appears at the bottom
of the activity diagram represents the final state—the end of the
workflow after the program performs its activities
12

Control Structures
• Rectangles with the upper-right corners folded over are called notes in
the UML
▫ Explanatory remarks that describe the purpose of symbols in the diagram
▫ Notes can be used in any UML diagram

• A dotted line connects each note with the element that the note
describes
13

Control Structures
• C++ provides three types of selection statements:
▫ The if selection statement either performs (selects) an action if a condition
(predicate) is true or skips the action if the condition is false
▫ The if…else selection statement performs an action if a condition is true
or performs a different action if the condition is false
▫ The switch selection statement performs one of many different actions,
depending on the value of an integer expression
14

Control Structures
• The if selection statement is a single-selection statement because it
selects or ignores a single action (or, a single group of actions)
• The if…else statement is called a double-selection statement because
it selects between two different actions (or groups of actions)
• The switch selection statement is called a multiple-selection statement
because it selects among many different actions (or groups of actions)
15

Control Structures
• C++ provides three types of repetition statements (also called looping
statements or loops) for performing statements repeatedly while a
condition (called the loop-continuation condition) remains true
• These are the while, do…while and for statements
• The while and for statements perform the action (or group of actions)
in their bodies zero or more times
• The do…while statement performs the action (or group of actions) in its
body at least once
16

Control Structures
• Each of the words if, else, switch, while, do and for is a C++
keyword
• These words are reserved by the C++ programming language to
implement various features, such as C++’s control statements
• Keywords cannot be used as identifiers, such as variable names
17
18

Control Structures
• Single-entry/single-exit control statements
▫ Control statements are attached to one another by connecting the exit point of one
to the entry point of the next
▫ Called control-statement stacking
▫ Only one other way to connect control statements—called control-statement
nesting, in which one control statement is contained inside another
19
20

if Selection Statement
• The following pseudocode determines whether “student’s grade is greater
than or equal to 60” is true or false
 If student’s grade is greater than or equal to 60
Print “Passed”

• The preceding pseudocode If statement can be written in C++ as


 if ( grade >= 60 )
cout << "Passed";

• The diamond or decision symbol indicates that a decision is to be made


21

Single-selection IF statement
22

if Selection Statement
• A decision can be based on any expression—if the expression evaluates to
zero, it’s treated as false; if the expression evaluates to nonzero, it’s
treated as true. For example the looping condition: while (true){ … }
• C++ provides the data type bool (Boolean) for variables that can hold only
the values true and false—each of these is a C++ keyword
23

if…else Double-Selection Statement


• Specifies an action to perform when the condition is true and a different
action to perform when the condition is false
• The following pseudocode prints “Passed” if the student’s grade is greater
than or equal to 60, or “Failed” if the student’s grade is less than 60.
If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”
• The preceding pseudocode If…Else statement can be written in C++ as
if (grade >= 60)
cout << "Passed";
else
cout << "Failed";
24

if…else Double-Selection Statement

if…else statement’s flow of control


25

if…else Double-Selection Statement


• Conditional operator (?:)
cout << ( grade >= 60 ? "Passed" : "Failed" );

▫ Closely related to the if…else statement, C++’s only ternary operator—it takes three operands
• The operands, together with the conditional operator, form a conditional expression
▫ The first operand is a condition
▫ The second operand is the value for the entire conditional expression if the condition is true
▫ The third operand is the value for the entire conditional expression if the condition is false
• The values in a conditional expression also can be actions to execute
26

if…else Double-Selection Statement


• Nested if…else statements test for multiple cases by placing if…else
selection statements inside other if…else selection statements
If student’s grade is greater than or equal to 90
Print “A”
Else
If student’s grade is greater than or equal to 80
Print “B”
Else
If student’s grade is greater than or equal to 70
Print “C”
Else
If student’s grade is greater than or equal to 60
Print “D”
Else
Print “F”
27

if…else Double-Selection Statement


• This pseudocode can be written in C++ as (notice the indentation)
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else
if ( studentGrade >= 80 ) // 80-89 gets "B" Q) Will the program give the
cout << "B"; same output if we removed
else
if ( studentGrade >= 70 ) // 70-79 gets "C" the else statements?
cout << "C";
else
if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";

• If studentGrade is greater than or equal to 90, the first four conditions are true, but
only the output statement after the first if condition is executed, all others will be
skipped
28

if…else Double-Selection Statement


• Some programmers write the preceding program as
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";

• The two forms are identical except for the spacing and indentation, which the compiler
ignores
• The latter form is popular because it avoids deep indentation of the code to the right,
which can force lines to wrap
29
30

if…else Double-Selection Statement


• The C++ compiler always associates an else with the immediately preceding if
unless told to do otherwise by the placement of braces { }
• This behavior can lead to what’s referred to as the dangling-else problem
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";

appears to indicate that if x is greater than 5, the nested if statement determines


whether y is also greater than 5
31

if…else Double-Selection Statement


• The compiler actually interprets the statement as
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";

• To force the nested if…else statement to execute as intended, use:


if ( x > 5 )
{
if ( y > 5 )
cout << "x and y are > 5";
}
else
cout << "x is <= 5";

• Braces { } indicate that the second if statement is in the body of the first if and
that the else is associated with the first if
32

if…else Double-Selection Statement


• To include several statements in the body of an if or in either part of an
if…else, enclose the statements in braces { }
• A set of statements contained within a pair of braces is called a
compound statement or a block
33

while Repetition Statement


• A repetition statement (also called a looping statement or a loop) allows
you to specify that a program should repeat an action while some
condition remains true
While there are more items on my shopping list
Purchase next item and cross it off my list
• “There are more items on my shopping list” is true or false
▫ If true, “Purchase next item and cross it off my list” is performed
▫ Eventually, the condition will become false, the repetition will terminate

while (condition) {
Statements …
}
34

while Repetition Statement


• Consider a program segment designed to find the first power of 3 that is
larger than 100. Suppose the integer variable product has been
initialized to 3.
• When the following while repetition statement finishes executing, the
variable product will contain the result
int product = 3;

while ( product <= 100 )


product = 3 * product;
35
36

while Repetition Statement


• This diagram introduces the UML’s merge
symbol, which joins two flows of activity into
one flow of activity
• The UML represents both the merge symbol
and the decision symbol as diamonds
• The merge symbol joins the transitions from
the initial state and from the action state, so
they both flow into the decision that
determines whether the loop should begin
(or continue) executing
37

Counter-Controlled Repetition
• We use counter-controlled repetition to input the grades one at a time
▫ This technique uses a variable called a counter to control the number of times a
group of statements will execute (also known as the number of iterations of the
loop)
▫ Often called definite repetition because the number of repetitions is known before
the loop begins executing
38

Counter-Controlled Repetition
• A total is a variable used to accumulate the sum of several values
• A counter is a variable used to count—in this case, the grade counter
indicates which of the 10 grades is about to be entered by the user
• Variables that are used to store totals are normally initialized to zero
before being used in a program; otherwise, the sum would include the
previous value stored in the total’s memory location
39
40
41
42

Note about Integer Division


• Dividing two integers results in integer division—any fractional part of
the calculation is truncated (discarded)
• For example, 1.75 will be considered as 1, the 0.75 is truncated
43

Numbers of Type "float or double"


• An averaging calculation is likely to produce a number with a decimal point—a
real number or floating-point number (e.g., 7.33, 0.0975 or 1000.12345)
• Type int cannot represent such a number
• C++ provides several data types for storing floating-point numbers in memory,
including float and double
• Compared to float variables, double variables can typically store numbers with
larger magnitude and finer detail
▫ more digits to the right of the decimal point—also known as the number’s precision
• Cast operator can be used to force the averaging calculation to produce a
floating-point numeric result
44

static_cast operator
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
int x,y; float z;
int x,y; float z;
x=3;
x=3;
y=2;
y=2;
z= x/y;
z= static_cast <float> (x)/y;
cout<< z <<endl;
cout<< z <<endl;
return 0;
return 0;
}
}
output: 1
output: 1.5
45

Numbers of Type “Double"


• Variables of type float represent single-precision floating-point
numbers and have seven significant digits on most of today’s systems
• Variables of type double represent double-precision floating-point
numbers
▫ These require twice as much memory as float variables and provide 15 significant
digits on most of today’s systems
▫ Approximately double the precision of float variables
• C++ treats all floating-point numbers in a program’s source code as
double values by default
▫ Known as floating-point literals
46

Numbers of Type “Unsigned Integer"


• In general, counters that should store only non-negative values should
be declared with unsigned types
• Variables of unsigned int types can represent values from 0 to
approximately twice the positive range of the corresponding signed
integer types
47

Note about Arithmetic Overflow


The integers could result in a value that’s too large to store in an int
variable.
• This is known as arithmetic overflow and causes undefined behavior,
which can lead to unintended results
48

Note about User Input


• Any time a program receives input from the user various problems might occur
cin >> grade; // input next grade
• we assume that the user will enter an integer grade in the range 0 to 100
• However, the person entering a grade could enter an integer less than 0, an integer
greater than 100, an integer outside the range of values that can be stored in an int
variable, a number containing a decimal point or a value containing letters, or a
special symbols that is not even an integer
• To ensure that the user’s input is valid, industrial-strength programs must test for all
possible erroneous cases
49

Sentinel-Controlled Repetition
• Let’s generalize the class average problem
▫ Develop a class average program that processes grades for an arbitrary number of students
each time it’s run
• The program must process an arbitrary number of grades
▫ How can the program determine when to stop the input of grades?
• Can use a special value called a sentinel value (also called a signal value, a
dummy value or a flag value) to indicate “end of data entry.”
• Sentinel-controlled repetition is often called indefinite repetition
▫ the number of repetitions is not known in advance
• The sentinel value must not be an acceptable input value
50

#include <iostream>

using namespace std;

int main()
{

cout << "Welcome to the grade book for\n" << "\n" << endl;
int total; // sum of grades entered by user
int gradeCounter; // number of grades entered
int grade; // grade value
double average; // number with decimal point for average
// initialization phase
total = 0; // initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// prompt for input and read grade from user
cout << "Enter grade or -1 to quit: ";
cin >> grade; // input grade or sentinel value
51

// loop until sentinel value read from user


while ( grade != -1 ) // while grade is not -1
{
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
// prompt for input and read next grade from user
cout << "Enter grade or -1 to quit: ";
cin >> grade; // input grade or sentinel value
}// end while
// termination phase
if (gradeCounter !=0 ) // if user entered at least one grade...
{
// calculate average of all grades entered
average = static_cast< double >( total ) / gradeCounter;
// display total and average (with two digits of precision)
cout << "\nTotal of all " << gradeCounter << " grades entered is " << total << endl;
cout << "Class average is " << setprecision (2) << fixed << average << endl;
} // end if
else // no grades were entered, so output appropriate message
cout << "No grades were entered" << endl;
return 0;
}
52
53

Sentinel-Controlled Repetition
• Without the braces, the last three statements in the body of the loop would
fall outside the loop, causing the computer to interpret this code incorrectly,
as follows:
while ( grade != -1 )
{total = total + grade;} // add grade to total

gradeCounter = gradeCounter + 1; // increment counter


cout << "Enter grade or -1 to quit: ";
cin >> grade;

• Good programming practice: use braces even if only one statement exists
inside the loop
54

Sentinel-Controlled Repetition
• The variable average is declared to be of type double to capture the fractional result
of our calculation
• total and gradeCounter are both int variables
• Recall that dividing two integers results in integer division, in which any fractional part of
the calculation is lost (i.e., truncated)
• In the following statement the division occurs first—the result’s fractional part is lost
before it’s assigned to average:
average = total / gradeCounter;
Compiler performs promotion (also called implicit conversion) on selected
operands
55

Sentinel-Controlled Repetition
• To perform a floating-point calculation with integers, create temporary
floating-point values.
• static_cast operator accomplishes this task
• The cast operator static_cast<double>(total) creates a
temporary floating-point copy of its operand in parentheses
▫ The value stored in total is still an integer
56

Sentinel-Controlled Repetition
• The call to setprecision in line 75 (with an argument of 2) indicates that
double values should be printed with two digits (could be rounded) of
precision to the right of the decimal point (e.g., 92.37)
▫ Parameterized stream manipulator (argument in parentheses)
▫ Programs that use these must include the header <iomanip>
• endl is a nonparameterized stream manipulator and does not require the
<iomanip> header file
• If the precision is not specified, floating-point values are normally output with
six digits of precision
57

Sentinel-Controlled Repetition
• Stream manipulator fixed indicates that floating-point values should
be output in fixed-point format, as opposed to scientific notation
• Fixed-point formatting is used to force a floating-point number to display
a specific number of digits
• Specifying fixed-point formatting also forces the decimal point and
trailing zeros to print, even if the value is a whole number amount, such
as 88.00
▫ Without the fixed-point formatting option, such a value prints in C++ as 88 without
the trailing zeros and decimal point
58

Sentinel-Controlled Repetition
• We could have also declared as unsigned int the variables grade,
total and average. Grades are normally values from 0 to 100, so the
total and average should each be greater than or equal to 0
• We declared those variables as int because we can’t control what the
user actually enters—the user could enter negative values
59

Nested Control Statements


• Consider the following problem statement:
▫ You’ve been asked to write a program to summarize the results. You’ve been given
a list of 10 students. Next to each name is written a 1 if the student passed the
exam or a 2 if the student failed
▫ Your program should analyze the results of the exam as follows:
1. Input each test result (i.e., a 1 or a 2). Display the prompting message “Enter
result” each time the program requests another test result
2. Count the number of test results of each type
3. Display a summary of the test results indicating the number of students who
passed and the number who failed
4. If more than eight students passed the exam, print the message “Bonus to
instructor!”
60
61
62
63
64

Nested Control Statements


• The if…else statement (lines 22–25) for processing each result is
nested in the while statement
• The if statement in lines 35–36 determines whether more than eight
students passed the exam and, if so, outputs the message "Bonus to
instructor!“
65

List Initialization
• C++11 introduces a new variable initialization syntax. List initialization (also called uniform
initialization) enables you to use one syntax to initialize a variable of any type

• Consider line 11 of the previous program:

unsigned int studentCounter = 1;

• In C++11, you can write this as

unsigned int studentCounter = { 1 };

• or

unsigned int studentCounter{ 1 };


66

List Initialization
• For fundamental-type variables, list-initialization syntax also prevents so-
called narrowing conversions that could result in data loss
• For example, previously you could write
int x = 12.7;
• which attempts to assign the double value 12.7 to the int variable x
• A double value is converted to an int, by truncating the floating-point
part (.7), which results in a loss of information—a narrowing conversion
67

Assignment Operators
• C++ provides several assignment operators for abbreviating assignment
expressions
• The += operator adds the value of the expression on the right of the
operator to the value of the variable on the left of the operator and
stores the result in the variable on the left of the operator
• Thus the assignment c += 3 adds 3 to c
68
69

Increment and Decrement Operators


• C++ also provides two unary operators for adding 1 to or subtracting 1
from the value of a numeric variable
• These are the unary increment operator, ++, and the unary decrement
operator, --
70
71
72
73

Operator precedence
74

Exercise 1: what is the output?


#include <iostream>
using namespace std;
int main()
{
int sum; // stores sum of integers 1 to 10
int x; // counter
x = 1; // count from 1
sum = 0; // initialize sum
while ( x <= 10 ) // loop 10 times
{
sum += x; // add x to sum
++x; // increment x The program calculates the sum
} // end while
cout << "The sum is: " << sum << endl;
of integers from 1 to 10
} // end main Output: 55
75

Exercise 2: what is the output?


#include <iostream> Output:
using namespace std;
1
int main()
{ 4
int y; // declare y 9
int x = 1; // initialize x
16
int total = 0; // initialize total
while ( x <= 10 ) // loop 10 times 25
{ 36
y = x * x; // perform calculation 49
cout << y << endl; // output result
64
total += y; // add y to total
x++; // increment counter x 81
} // end while 100
cout << "Total is " << total << endl; // display result
Total is 385
} // end main
76

Exercise 3: what is the output?


#include <iostream> The program calculates the
using namespace std;
int main()
value of the product and sum
{ Output:
int x = 5; Value of product after calculation: 25
int product = 5; Value of x after calculation: 6
int quotient = 12; Value of quotient after calculation: 2
// part a Value of x after calculation: 6
product *= x++; // part a statement
cout << "Value of product after calculation: " << product << endl;
cout << "Value of x after calculation: " << x << endl << endl;
// part b
x = 5; // reset value of x
quotient /= ++x; // part b statement
cout << "Value of quotient after calculation: " << quotient << endl;
cout << "Value of x after calculation: " << x << endl << endl;
} // end main
77

Exercise 4:
Display the following shape using a loop
#include<iostream>
using namespace std;

int main(void)
{
int counter=1;
while (counter <=7){
cout << "* \t\t *" << endl;
counter++;
}
}
78

Exercise 5: Ternary operator


#include<iostream>
using namespace std;

int main(void)
{ Note:
double price = 2.45; (int) is similar to static_cast(int)
int dolar = (int)price;
int ct = (price-dolar) * 100;
cout<< ct <<" "<< dolar<<" "<< (dolar > 50 ? 'A' : 'B')<<endl;
}
The program extracts the fraction from
“price”, multiplies it by 100, then
compare it with 50
Output: 45 2 B
79

Exercise 6: Raise to the power


// Raise x to the y power cout << "Enter base as an integer: "; // prompt
#include <iostream> for base
using namespace std; cin >> x; // input base
int main() cout << "Enter exponent as an integer: "; //
prompt for exponent
{
cin >> y; // input exponent
int x; // base
// count from 1 to y and multiply power by x
int y; // exponent
each time
int i; // counts from 1 to y
while ( i <= y )
{ Sample output:
// calculate x raised to power y x = 2
power *= x;
int power; Y = 3
++i; The result is 8 (23)
// initialize i to begin counting from 1
} // end while
i = 1; power = 1; // initialize power
cout << power << endl; // display result
} // end main
80

Exercise 7: Tabular Output


Write a C++ program that uses a while statement and the tab escape sequence \t to
print the following table of values:

N 10*N 100*N 1000*N #include <iostream>


using namespace std;
1 10 100 1000
int main()
2 20 200 2000 {
3 30 300 3000 cout<<"n\t"<<"n*10\t"<<"n*100\t"<<"n*1000\t"<<endl;
int n=1;
4 40 400 4000 while (n<=5){
5 50 500 5000 cout<<n<<"\t"<<n*10<<"\t"<<n*100<<"\t"<<n*1000<<endl;
n++;
}
return 0;
}

You might also like