C++ Programming: From Problem
Analysis to Program Design, Fifth Edition
Chapter 1: An Overview of
Computers and Programming
Languages
Updated by: Malak Abdullah
The Evolution of Programming Languages
(cont'd.)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 2
Processing a C++ Program
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 3
Processing a C++ Program (cont'd.)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 4
Processing a C++ Program (cont'd.)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 5
Processing a C++ Program (cont'd.)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 6
Programming with the Problem Analysis–
Coding–Execution Cycle
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 7
The Problem Analysis–Coding–Execution
Cycle (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 8
The Problem Analysis–Coding–Execution
Cycle (cont'd.)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 9
The Problem Analysis–Coding–Execution
Cycle (cont'd.)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 10
Example 1-1
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 11
Example 1-1 (cont'd.)
Algorithm:
Get length of the rectangle
Get width of the rectangle
Find the perimeter using the following equation:
perimeter = 2 * (length + width)
Find the area using the following equation:
area = length * width
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 12
WAP a C++ Program
parameter = 2 * (length + width)
area = length * width
#include <iostream>
using namespace std;
int main()
{
int length, width, parameter, area; // variables
cout << "Enter length & Width: ";
cin >> length >> width;
parameter = 2 * (length + width);
area = length * width;
cout << "Parameter is :" << parameter << endl;
cout << "Area is :" << area << endl;
return 0;
}
Sample Run:
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Updated by: Malak Abdullah 13
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
Chapter 2: Basic Elements of C++
Objectives
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2
Objectives (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 3
The Basics rule of a C++ Program
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 4
Comments
• Comments are for the reader, not the compiler
• Two types:
− Single line
// This is a C++ program. It prints the sentence:
// Welcome to C++ Programming.
− Multiple line
/*
You can include comments that can
occupy several lines.
*/
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5
Special Symbols
• Special symbols
+ ?
- ,
* <=
/ != not equal to
. == equal to
; >=
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 6
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7
Identifiers
• Consist of letters, digits, and the underscore
character (_)
• Must begin with a letter or underscore
• C++ is case sensitive
− NUMBER is not the same as number
• Two predefined identifiers are cout and cin
• Unlike reserved words, predefined identifiers
may be redefined, but it is not a good idea
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8
Data Types
• Data type: set of values together with a set of
operations
• C++ data types fall into three categories:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9
Simple Data Types
• Three categories of simple data
− Integral: integers (numbers without a decimal)
− Floating-point: decimal numbers
− Enumeration type: user-defined data type
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10
Simple Data Types (continued)
• Integral data types are further classified into
nine categories:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 11
Simple Data Types (continued)
• 1 byte = 8 bits
• Bit = smallest unit of data 1 or 0
• Different compilers may allow different ranges
of values
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12
int Data Type
• Examples:
-6728
0
78
+763
• Positive integers do not need a + sign
• No commas are used within an integer
− Commas are used for separating items in a list
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 13
bool Data Type
• bool type
− Two values: true and false
− Manipulate logical (Boolean) expressions
• true and false are called logical values
• bool, true, and false are reserved words
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 14
char Data Type
• The smallest integral data type
• Used for characters: letters, digits, and special
symbols
• Each character is enclosed in single quotes
− 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character and is written ' ',
with a space left between the single quotes
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 15
Floating-Point Data Types
• C++ uses scientific notation to represent real
numbers (floating-point notation)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16
Floating-Point Data Types
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 17
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 18
Type Conversion (Casting)
• Implicit type coercion: when value of one type
is automatically changed to another type
• Cast operator: provides explicit type
conversion
static_cast<dataTypeName>(expression)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19
Type Conversion (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20
string Type
• Programmer-defined type supplied in
ANSI/ISO Standard C++ library
• Sequence of zero or more characters
• Enclosed in double quotation marks
• Null: a string with no characters
• Each character has relative position in string
− Position of first character is 0
• Length of a string is number of characters in it
− Example: length of "William Jacob" is 13
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21
Input
• Data must be loaded into main memory
before it can be manipulated
• Storing data in memory is a two-step process:
− Instruct computer to allocate memory
− Include statements to put data into memory
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22
Allocating Memory with Constants
and Variables
• Named constant: memory location whose
content can’t change during execution
• The syntax to declare a named constant is:
• In C++, const is a reserved word
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23
Allocating Memory with Constants
and Variables (continued)
• Variable: memory location whose content
may change during execution
• The syntax to declare a named constant is:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24
Assignment Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25
Assignment Statement (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26
Declaring & Initializing Variables
• Variables can be initialized when declared:
int first=13, second=10;
char ch=' ';
double x=12.6;
• All variables must be initialized before they
are used
− But not necessarily during declaration
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 27
Input (Read) Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28
Variable Initialization
• There are two ways to initialize a variable:
int feet;
− By using the assignment statement
feet = 35;
− By using a read statement
cin >> feet;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 29
Increment & Decrement Operators
x = 5; x = 5;
y = ++x; y = x++;
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 30
Output
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 31
Output (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 32
Output (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 33
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 34
Preprocessor Directives
(continued)
• Syntax to include a header file:
• For example:
#include <iostream>
− Causes the preprocessor to include the
header file iostream in the program
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 35
namespace and Using cin and
cout in a Program
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 36
Using the string Data Type in a
Program
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 37
Program Style and Form
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 38
Use of Semicolons, Brackets, and
Commas
• All C++ statements end with a semicolon
− Also called a statement terminator
• { and } are not C++ statements
• Commas separate items in a list
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 39
Prompt Lines
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 40
Documentation
• A well-documented program is easier to
understand and modify
• You use comments to document programs
• Comments should appear in a program to:
− Explain the purpose of the program
− Identify who wrote it
− Explain the purpose of particular statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 41
More on Assignment Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 42
Summary ch-2
• C++ program: collection of functions where
each program has a function called main
• Identifier consists of letters, digits, and
underscores, and begins with letter or
underscore
• The arithmetic operators in C++ are
addition (+), subtraction (-),multiplication (*),
division (/), and modulus (%)
• Arithmetic expressions are evaluated using the
precedence associativity rules
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 43
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 44
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 45
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
Chapter 3: Input/Output
Objectives
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2
Objectives (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 3
I/O Streams and Standard I/O
Devices
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 4
I/O Streams and Standard I/O
Devices (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5
I/O Streams and Standard I/O
Devices (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 6
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7
cin and the Extraction Operator >>
(continued)
• Entering a char value into an int or double
variable causes serious errors, called input
failure
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8
cin and the Extraction Operator
>> (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10
Using Predefined Functions in a
Program (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 11
Using Predefined Functions in a
Program (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12
Using Predefined Functions in a
Program (continued)
Sample Run:
Line 1: 2 to the power of 6 = 64
Line 4: 12.5 to the power of 3 = 1953.13
Line 5: Square root of 24 = 4.89898
Line 7: u = 181.019
Line 9: Length of str = 20
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 14
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 15
cin and the ignore Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16
putback and peek Functions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 17
putback and peek Functions
(continued)
• The syntax for putback:
− istreamVar: an input stream variable (cin)
− ch is a char variable
• The syntax for peek:
− istreamVar: an input stream variable (cin)
− ch is a char variable
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 18
The Dot Notation Between I/O
Stream Variables and I/O Functions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19
Input Failure
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20
The clear Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21
Output and Formatting Output
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22
setprecision Manipulator
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23
fixed Manipulator
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24
showpoint Manipulator
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25
setw
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26
Additional Output Formatting
Tools
• Additional formatting tools that give you more
control over your output:
− setfill manipulator
− left and right manipulators
− unsetf manipulator
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 27
setfill Manipulator
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28
left and right Manipulators
• left: left-justifies the output
• Disable left by using unsetf
• right: right-justifies the output
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 29
Types of Manipulators
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 30
Input/Output and the string
Type
• An input stream variable (cin) and >>
operator can read a string into a variable of
the data type string
• Extraction operator
− Skips any leading whitespace characters and
reading stops at a whitespace character
• The function getline
− Reads until end of the current line
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 31
File Input/Output
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 32
Summary
• Stream: infinite sequence of characters from
a source to a destination
• Input stream: from a source to a computer
• Output stream: from a computer to a
destination
• cout: command output <<
• cin: command input. >>
• To use cin and cout, <#include iostream>
header
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 33
Summary (continued)
• get reads data character-by-character
• putback puts last character retrieved by get
back to the input stream
• ignore skips data in a line //
• peek returns next character from input
stream, but does not remove it.
• Attempting to read invalid data into a variable
causes the input stream to enter the fail state
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 34
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 35
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
Objectives
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2
Control Structures
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 3
Control Structures (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 4
Relational Operators
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5
Relational Operators (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 6
Relational Operators and Simple
Data Types
• You can use the relational operators with all
three simple data types:
− 8 < 15 evaluates to true
− 6 != 6 evaluates to false
− 2.5 > 5.8 evaluates to false
− 5.9 <= 7.5 evaluates to true
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7
Comparing Characters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8
Relational Operators and the
string Type
• Relational operators can be applied to strings
• Strings are compared character by character,
starting with the first character
• Comparison continues until either a mismatch
is found or all characters are found equal.
• If two strings of different lengths are compared
and the comparison is equal to the last
character of the shorter string
− The shorter string is less than the larger string
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9
Relational Operators and the
string Type (continued)
• Suppose we have the following declarations:
string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str5 = "Big";
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10
Logical (Boolean) Operators and
Logical Expressions
• Logical (Boolean) operators enable you to
combine logical expressions
unary. !, +, -
binary
binary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 11
Logical (Boolean) Operators and
Logical Expressions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12
Order of Precedence
• Relational and logical operators are
evaluated from left to right
• The associativity is left to right
• Parentheses can override precedence
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 13
Order of Precedence (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 14
Order of Precedence (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 15
Short-Circuit Evaluation
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16
int Data Type and Logical
(Boolean) Expressions
• Earlier versions of C++ did not provide built-in
data types that had Boolean values
• Logical expressions evaluate to either 1 or 0
− The value of a logical expression was stored
in a variable of the data type int
• You can use the int data type to manipulate
logical (Boolean) expressions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 17
The bool Data Type and Logical
(Boolean) Expressions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 18
Example
• #include <iostream>
• int main()
• {
• int num;
• std::cout << "Enter a number: ";
• std::cin>>num;
• if(0 <= num && num <= 10)
• {
• std::cout<< "Positive";
• }
• else
• {
• std::cout<<"Negetive";
• }
• return 0;
• }
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19
Selection: if and if...else
• One-Way Selection (if)
• Two-Way Selection (if … else)
• Compound (Block of) Statements
• Multiple Selections: Nested if
• Comparing if...else Statements with a
Series of if Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20
Selection: if and if...else
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22
One-Way Selection (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23
Two-Way Selection
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25
Two-Way Selection (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26
Example
#include <iostream>
int main()
{
int hour, rate =5;
std::cout << "Enter a hour: ";
std::cin>>hour;
if(hour > 40 )
{
int wages = 40.0 *rate +1.5 * rate *(hour -40.0);
std::cout<< +wages;
}
else
{
int wages = hour * rate;
std::cout<< +wages;
}
return 0;
} C++ Programming: From Problem Analysis to Program Design, Fourth Edition 27
Compound (Block of) Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28
Compound (Block of) Statement
(continued)
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter a age: ";
cin>>age;
if(age > 18 )
{
cout << "Eligible to vote." << endl;
cout << "No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << "Still a minor." << endl;
}
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 29
• Nesting: one control statement in another
control statement.
• An else is associated with the most recent
if that has not been paired with an else
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 30
Example
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter the score: ";
cin>>score;
if(score >= 90 )
{
cout << "The grade is A." << endl;
}
else if (score >= 80)
{
cout << "The grade is B." << endl;
}
else if (score >= 70)
{
cout << "The grade is C." << endl;
}
else if (score >= 60)
{
cout << "The grade is D." << endl;
}
else
cout << "The grade is Failed." <<endl;
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 31
Using Pseudocode to Develop,
Test, and Debug a Program
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 32
Input Failure and the if Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 33
Confusion Between == and =
• C++ allows you to use any expression that
can be evaluated to either true or false as
an expression in the if statement:
if (x = 5)
cout << "The value is five." << endl;
• The appearance of = in place of ==
resembles a silent killer
− It is not a syntax error
− It is a logical error
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 34
Conditional Operator (?:)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 35
Conditional operator example
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 36
Start from here
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 37
switch Structures (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 39
#include <iostream>
using namespace std;
int main() {
char grade;
cout << "Enter an grade: ";
cin >> grade;
switch (grade) {
case 'A':
cout << "The grade is 4.0";
break;
case 'B':
cout << "The grade is 3.0";
break;
case 'C':
cout << "The grade is 2.0";
break;
case 'D':
cout << "The grade is 1.0";
break;
case 'F':
cout << "The grade is 0.0";
break;
default:
cout << "The grade is invalid";
break;
}
return 0;
}
WAP in C++ for calculator for 2 number:
#include <iostream>
using namespace std;
int main()
{
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper)
{
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 41
Summary
• Control structures alter normal control flow
• Most common control structures are selection
and repetition
• Relational operators: ==, <, <=, >, >=, !=
• Logical expressions evaluate to 1 (true) or 0
(false)
• Logical operators: ! (not), && (and), || (or)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 42
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 43
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 44
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
Objectives
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2
Why is Repetition Needed?
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 3
while Looping (Repetition)
Structure
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 4
while Looping (Repetition)
Structure (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5
• If you know exactly how many pieces of data
need to be read, the while loop becomes a
counter-controlled loop
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 6
• Sentinel variable is tested in the condition
and loop ends when sentinel is encountered
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8
Number Guessing Game
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9
• Use an EOF (End Of File)-controlled while loop
• The logical value returned by cin can determine
if the program has ended input
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10
eof Function
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 11
for Looping (Repetition)
Structure
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12
for Looping (Repetition)
Structure (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 13
for Looping (Repetition)
Structure (continued)
Output:
0,1,2,3,4,5,6,7,8,9
Hello
*
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 14
do…while Looping (Repetition)
Structure
• General form of a do...while:
• The statement executes first, and then the
expression is evaluated
• To avoid an infinite loop, body must contain a
statement that makes the expression false.
• The statement can be simple or compound
• Loop always iterates at least once.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 15
do…while Looping (Repetition)
Structure (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16
do…while Looping (Repetition)
Structure (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 17
Choosing the Right Looping
Structure
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19
break and continue Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20
break & continue Statements
(continued)
• continue is used in while, for, and
do…while structures
• When executed in a loop
− It skips remaining statements and proceeds
with the next iteration of the loop
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21
Nested Control Structures
• To create the following pattern:
*
**
***
****
*****
• We can use the following code:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22
Nested Control Structures
(continued)
• What is the result if we replace the first for
statement with the following?
for (i = 5; i >= 1; i--){
for (j = 1; j <= i; j++)
{cout << "*";
cout << endl;}}
• Answer:
*****
****
***
**
*
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
Chapter 6: User-Defined Functions I
Objectives
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2
Introduction
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 3
Introduction (continued)
• Functions
− Called modules
− Like miniature programs
− Can be put together to form a larger program
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 4
• In algebra, a function is defined as a rule or
correspondence between values, called the
function’s arguments, and the unique value of
the function associated with the arguments
− If f(x) = 2x + 5, then f(1) = 7,
f(2) = 9, and f(3) = 11
• 1, 2, and 3 are arguments
• 7, 9, and 11 are the corresponding values
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 6
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9
Predefined Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10
Predefined Functions (continued)
• Example 6-1 sample run:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 13
Value-Returning Functions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 14
Value-Returning Functions
(continued)
• Because the value returned by a value-
returning function is unique, we must:
− Save the value for further calculation
− Use the value in some calculation
− Print the value
• A value-returning function is used in an
assignment or in an output statement
• One more thing is associated with functions:
− The code required to accomplish the task
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 15
Value-Returning Functions
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16
Value-Returning Functions
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 17
Syntax: Value-Returning Function
• Syntax:
• functionType is also called the data type
or return type.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 18
Syntax: Formal Parameter List
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19
Function Call
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20
Syntax: Actual Parameter List
• The syntax of the actual parameter list is:
• Formal parameter list can be empty:
• A call to a value-returning function with an
empty formal parameter list is:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21
return Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22
Syntax: return Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23
Function Prototype
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25
Function Prototype (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 27
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28
Palindrome Number (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 29
Flow of Execution
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 30
Flow of Execution (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 31
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 32
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 33
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 34
C++ Programming:
From Problem Analysis
to Program Design, Fourth Edition
Chapter 7: User-Defined Functions II
Objectives
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2
Objectives (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 3
Void Functions
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 4
Void Functions (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5
Void Functions without Parameters
• Function definition syntax:
• void is a reserved word
• Function call syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 6
Void Functions with Parameters
• Function definition syntax:
• Formal parameter list syntax:
• Function call syntax:
• Actual parameter list syntax:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7
Void Functions with Parameters
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8
Void Functions with Parameters
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9
Value Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 11
Reference Variables as Parameters
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 15
Scope of an identifier/variable
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16
Scope of an Identifier (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 17
Write a C++ program global variable & Local variable with
scope resolution operator ::
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 18
Scope of an Identifier (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19
Global Variables, Named
Constants, and Side Effects
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20
Static and Automatic Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21
Static and Automatic Variables
(continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23
Function Overloading (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24
Function Overloading (continued)
• The following functions all have different
formal parameter lists:
• The following functions have the same formal
parameter list:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25
Function Overloading (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26
Write a c++ for method overloading.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 27
Function Overloading (continued)
• Correct function overloading:
• Syntax error:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28
Functions with Default Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 29
Functions with Default Parameters
(continued)
• Consider the following prototype:
• Assume:
− a, b are int, ch is char, d is double
• Examples of legal calls:
• Examples of illegal calls:
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 30
Summary
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 31
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 32
Summary (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 33