SlideShare a Scribd company logo
9781337117562_ppt_ch01.pptx
Chapter 1
An Overview of Computers and Programming Languages
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
C++ Programming: Program Design Including Data Structures,
Eighth Edition
‹#›
Objectives (1 of 2)
In this chapter, you will:
Learn about different types of computers
Explore the hardware and software components of a computer
system
Learn about the language of a computer
Learn about the evolution of programming languages
Examine high-level programming languages
Discover what a compiler is and what it does
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
Objectives (2 of 2)
Examine a C++ program
Explore how a C++ program is processed
Learn what an algorithm is and explore problem-solving
techniques
Become aware of structured design and object-oriented design
programming methodologies
Become aware of Standard C++, ANSI/ISO Standard C++,
C++11, and C++14
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
Introduction
Without software, a computer is useless
Software is developed with programming languages
C++ is a programming language
C++ is suited for a wide variety of programming tasks
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
4
A Brief Overview of the History of Computers (1 of 3)
Early calculation devices
Abacus
Pascaline
Leibniz device
Jacquard’s weaving looms
Babbage machines: difference and analytic engines
Hollerith machine
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
5
A Brief Overview of the History of Computers (2 of 3)
Early computer-like machines
Mark I
Electronic Numerical Integrator and Calculator (ENIAC)
Von Neumann architecture
Universal Automatic Computer (UNIVAC)
Transistors and microprocessors
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
6
A Brief Overview of the History of Computers (3 of 3)
Categories of computers
Mainframe computers
Midsize computers
Micro computers (personal computers)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
7
Elements of a Computer System
Two main components
Hardware
Software
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
8
Hardware
Central processing unit (CPU)
Main memory (MM) or random access memory (RAM)
Secondary storage
Input/output devices
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
9
Central Processing Unit and Main Memory (1 of 4)
Central processing unit
Brain of the computer
Most expensive piece of hardware
Operations
Carries out arithmetic and logical operations
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
10
Central Processing Unit and Main Memory (2 of 4)
FIGURE 1-1 Hardware components of a computer and main
memory
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
11
Central Processing Unit and Main Memory (3 of 4)
Random access memory (or main memory) is directly connected
to the CPU
All programs must be loaded into main memory before they can
be executed
All data must be brought into main memory before it can be
manipulated
When computer power is turned off, everything in main memory
is lost
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
12
Central Processing Unit and Main Memory (4 of 4)
Main memory is an ordered sequence of memory cells
Each cell has a unique location in main memory, called the
address of the cell
Each cell can contain either a programming instruction or data
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
13
Secondary Storage
Secondary storage: device that stores information permanently
Examples of secondary storage
Hard disks
Flash drives
CD-ROMs
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
14
Input/Output Devices
Input devices feed data and programs into computers
Keyboard
Mouse
Scanner
Camera
Secondary storage
Output devices display results
Monitor
Printer
Secondary storage
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
15
Software
Software are programs written to perform specific tasks
System programs control the computer
Operating system monitors the overall activity of the computer
and provides services such as:
Memory management
Input/output activities
Storage management
Application programs perform a specific task
Word processors
Spreadsheets
Games
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
16
The Language of a Computer (1 of 4)
Analog signals: continuously varying continuous wave forms
Digital signals: sequences of 0s and 1s
Machine language: language of a computer
A sequence of 0s and 1s
Binary digit (bit): the digit 0 or 1
Binary code (binary number): a sequence of 0s and 1s
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
17
The Language of a Computer (2 of 4)
Byte: a sequence of eight bits
Kilobyte (KB): 210 bytes = 1024 bytes
ASCII (American Standard Code for Information Interchange)
128 characters
A is encoded as 1000001 (66th character)
The character 3 is encoded as 0110011 (51st character)
Number systems
The decimal system (base 10) is used in our daily life
The computer uses the binary (or base 2) number system
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
18
The Language of a Computer (3 of 4)
TABLE 1-1 Binary Units UnitSymbolBits/BytesByte8
bitsKilobyteKB210 bytes = 1024 bytesMegabyteMB1024 KB =
210 KB = 220 bytes = 1,048,576 bytesGigabyteGB1024MB =
210 MB = 230 bytes = 1,073,741,824 bytesTerabyteTB1024 GB
= 210 GB = 240 bytes = 1,099,511,627,776
bytesPetabytePB1024 TB = 210 TB = 250 bytes =
1,125,899,906,842,624 bytesExabyteEB1024 PB = 210 PB =
260 bytes = 1,152,921,504,606,846,976 bytesZettabyteZB1024
EB5 210 EB = 270 bytes = 1,180,591,620,717,411,303,424
bytes
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
The Language of a Computer (4 of 4)
Unicode is another coding scheme
65,536 characters
Two bytes (16 bits) to store a character
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
20
The Evolution of Programming Languages (1 of 3)
Early computers were programmed in machine language
To calculate wages = rate * hours in machine language:
100100 010001 //Load
100110 010010 //Multiply
100010 010011 //Store
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
21
The Evolution of Programming Languages (2 of 3)
Assembly language instructions are mnemonic
Instructions are written in an easy-to-remember form
An assembler translates a program written in assembly language
into machine language
Using assembly language instructions, wages = rate * hours can
be written as:
LOAD rate
MULT hours
STOR wages
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
22
The Evolution of Programming Languages (3 of 3)
High-level languages include Basic, FORTRAN, COBOL, C,
C++, C#, Java, and Python
Compiler: translates a program written in a high-level language
into machine language
In C++, the weekly wages equation can be written as:
wages = rate * hours;
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
23
Processing a C++ Program (1 of 4)
#include <iostream>
using namespace std;
int main()
{
cout << "My first C++ program." << endl;
return 0;
}
Sample Run:
My first C++ program.
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
24
Processing a C++ Program (2 of 4)
Steps needed to process a C++ program
Use a text editor to create the source code (source program) in
C++
Include preprocessor directives
Begin with the symbol # and are processed by the preprocessor
Use the compiler to:
Check that the program obeys the language rules
Translate the program into machine language (object program)
Use an integrated development environment (IDE) to develop
programs in a high-level language
Programs such as mathematical functions are available
The library contains prewritten code you can use
A linker combines object program with other programs in the
library to create executable code
The loader loads executable program into main memory
The last step is to execute the program
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
25
Processing a C++ Program (3 of 4)
IDEs are quite user friendly
Compiler identifies the syntax errors and also suggests how to
correct them
Build or Rebuild is a simple command that links the object code
with the resources used from the IDE
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
26
Processing a C++ Program (4 of 4)
FIGURE 1-2 Processing a C++ program
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
27
Programming with the Problem Analysis–Coding–Execution
Cycle
Programming is a process of problem solving
An algorithm is a step-by-step problem-solving process
A solution is achieved in a finite amount of time
FIGURE 1-3 Problem analysis–coding–execution cycle
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
28
The Problem Analysis–Coding–Execution Cycle (1 of 5)
Step 1: Analyze the problem
Outline the problem and its requirements
Design steps (algorithm) to solve the problem
Step 2: Implement the algorithm
Implement the algorithm in code
Verify that the algorithm works
Step 3: Maintain the program
Use and modify the program if the problem domain changes
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
29
The Problem Analysis–Coding–Execution Cycle (2 of 5)
Analyze the problem using these steps:
Step 1: Thoroughly understand the problem and all requirements
Step 2: Understand the problem requirements
Does program require user interaction?
Does program manipulate data?
What is the output?
Step 3: If complex, divide the problem into subproblems
Analyze and design algorithms for each subproblem
Check the correctness of algorithm
Test the algorithm using sample data
Some mathematical analysis might be required
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
30
The Problem Analysis–Coding–Execution Cycle (3 of 5)
Once the algorithm is designed and correctness is verified
Write the equivalent code in high-level language
Enter the program using a text editor
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
31
The Problem Analysis–Coding–Execution Cycle (4 of 5)
Run code through the compiler
If compiler generates errors
Look at code and remove errors
Run code again through compiler
If there are no syntax errors
Compiler generates equivalent machine code
Link machine code with the system’s resources
Performed by the linker
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
32
The Problem Analysis–Coding–Execution Cycle (5 of 5)
Once compiled and linked, the loader can place program into
main memory for execution
The final step is to execute the program
Compiler guarantees that the program follows the rules of the
language
Does not guarantee that the program will run correctly
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
33
Example 1-1 (1 of 2)
Design an algorithm to find the perimeter and area of a
rectangle
The perimeter and area of the rectangle are given by the
following formulas:
perimeter = 2 * (length + width)
area = length * width
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
34
Example 1-1 (2 of 2)
Algorithm
Get the length of the rectangle
Get the width of the rectangle
Find the perimeter with this equation:
perimeter = 2 * (length + width)
Find the area with this equation:
area = length * width
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
35
Example 1-5 (1 of 4)
Calculate each student’s grade
There are 10 students in a class
Each student has taken five tests
Each test is worth 100 points
Design algorithms to:
Calculate the grade for each student and class average
Find the average test score
Determine the grade
Use the provided data: students’ names and test scores
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
36
Example 1-5 (2 of 4)
Algorithm to determine the average test score
Get the five test scores
Add the five test scores
The sum of the test scores is represented by sum
Suppose average stands for the average test score:
average = sum / 5;
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
37
Example 1-5 (3 of 4)
Algorithm to determine the grade:
if average is greater than or equal to 90
grade = A
otherwise
if average is greater than or equal to 80 and less than 90
grade = B
otherwise
if average is greater than or equal to 70 and less than 80
grade = C
otherwise
if average is greater than or equal to 60 and less than 70
grade = D
otherwise
grade = F
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
38
Example 1-5 (4 of 4)
Main algorithm is presented below:
totalAverage = 0;
Repeat the following for each student:
Get student’s name
Use the algorithm to find the average test score
Use the algorithm to find the grade
Update totalAverage by adding current student’s average test
score
Determine the class average as follows:
classAverage = totalAverage / 10
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
39
Programming Methodologies
Two popular approaches to programming design
Structured
Object-oriented
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
40
Structured Programming
Structured design
Involves dividing a problem into smaller subproblems
Structured programming
Involves implementing a structured design
The structured design approach is also called:
Top-down (or bottom-up) design
Stepwise refinement
Modular programming
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
41
Object-Oriented Programming (1 of 3)
Object-oriented design (OOD)
Identify components called objects
Determine how objects interact with each other
Specify relevant data and possible operations to be performed
on that data
Each object consists of data and operations on that data
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
42
Object-Oriented Programming (2 of 3)
An object combines data and operations on the data into a single
unit
A programming language that implements OOD is called an
object-oriented programming (OOP) language
To design and use objects, you must learn how to:
Represent data in computer memory
Manipulate data
Implement operations
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
43
Object-Oriented Programming (3 of 3)
To create operations:
Write algorithms and implement them in a programming
language
Use functions to implement algorithms
Learn how to combine data and operations on the data into a
single unit called a class
C++ was designed to implement OOD
OOD is used with structured design
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
44
ANSI/ISO Standard C++
C++ evolved from C
C++ designed by Bjarne Stroustrup at Bell Laboratories in early
1980s
Many different C++ compilers were available
C++ programs were not always portable from one compiler to
another
In mid-1998, ANSI/ISO C++ language standards were approved
Second standard, called C++11, was approved in 2011
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
45
Quick Review (1 of 3)
A computer is an electronic device that can perform arithmetic
and logical operations
A computer system has hardware and software components
The central processing unit (CPU) is the brain
Primary storage (MM) is volatile; secondary storage (e.g., disk)
is permanent
The operating system monitors overall activity of the computer
and provides services
There are various kinds of languages
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
46
Quick Review (2 of 3)
Compiler: translates high-level language into machine code
Algorithm:
Step-by-step problem-solving process
Arrives at a solution in a finite amount of time
Problem-solving process
Analyze the problem and design an algorithm
Implement the algorithm in code
Maintain the program
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
47
Quick Review (3 of 3)
Structured design
Problem is divided into smaller subproblems
Each subproblem is solved
Combine solutions to all subproblems
Object-oriented design (OOD) program: a collection of
interacting objects
Object: data and operations on those data
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom use.
‹#›
48
9781337117562_ppt_ch02.pptx
Chapter 2
Basic Elements of C++
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
C++ Programming: Program Design Including Data Structures,
Eighth Edition
‹#›
Objectives (1 of 3)
In this chapter, you will:
Become familiar with the basic components of a C++ program,
including functions, special symbols, and identifiers
Explore simple data types
Discover how to use arithmetic operators
Examine how a program evaluates arithmetic expressions
Become familiar with the string data type
Learn what an assignment statement is and what it does
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
2
‹#›
2
Objectives (2 of 3)
Learn about variable declaration
Discover how to input data into memory using input statements
Become familiar with the use of increment and decrement
operators
Examine ways to output results using output statements
Learn how to use preprocessor directives and why they are
necessary
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
3
‹#›
Objectives (3 of 3)
Learn how to debug syntax errors
Explore how to properly structure a program, including using
comments to document a program
Become familiar with compound statements
Learn how to write a C++ program
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
4
‹#›
Introduction
Computer program
A sequence of statements whose objective is to accomplish a
task
Programming
The process of planning and creating a program
Real-world analogy: a recipe for cooking
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
5
‹#›
5
A Quick Look at a C++ Program (1 of 5)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
6
‹#›
6
A Quick Look at a C++ Program (2 of 5)
Sample Run:
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
7
‹#›
7
A Quick Look at a C++ Program (3 of 5)
FIGURE 2-1 Various parts of a C++ program
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
8
‹#›
8
A Quick Look at a C++ Program (4 of 5)
FIGURE 2-1 Various parts of a C++ program (cont’d.)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
9
‹#›
9
A Quick Look at a C++ Program (5 of 5)
Variable: a memory location whose contents can be changed
FIGURE 2-3 Memory allocation
FIGURE 2-4 Memory spaces after the statement length = 6.0;
executes
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
10
‹#›
10
The Basics of a C++ Program
Subprogram (or function): collection of statements
When executed, accomplishes something
May be predefined or standard
Syntax rules: rules that specify which statements (instructions)
are legal or valid
Semantic rules: determine the meaning of the instructions
Programming language: a set of rules, symbols, and special
words
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
11
‹#›
11
Comments
Comments are for the reader, not the compiler
Two types
Single line: begins with //
//***************************************************
***********
// Given the length and width of a rectangle, this C++ program
// computes and outputs the perimeter and area of the rectangle.
//***************************************************
***********
Multiple line: enclosed between /* and */
/*
You can include comments that can
occupy several lines.
*/
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
12
‹#›
12
Special Symbols
A token is the smallest individual unit of a program written in
any language
C++ tokens include special symbols, word symbols, and
identifiers
Special symbols in C++ include:
+-*/
.;?,
<=!===>=
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
13
‹#›
13
Reserved Words (Keywords)
Reserved word symbols (or keywords):
Cannot be redefined within a program
Cannot be used for anything other than their intended use
Examples include:
int
float
double
char
const
void
return
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
14
‹#›
14
Identifiers (1 of 2)
An identifier is the name of something that appears in a
program
Consists 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
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
15
‹#›
15
Identifiers (2 of 2)
Legal identifiers in C++
first
conversion
payRate
TABLE 2-1 Examples of Illegal IdentifiersIllegal
IdentifierReasonA Correct Identifieremployee SalaryThere can
be no space between
employee and Salary.employeeSalaryHello!The exclamation
mark cannot be used in an identifier.Helloone+twoThe symbol +
cannot be used in an identifier.onePlusTwo2ndAn identifier
cannot begin with a digit.second
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
16
‹#›
16
Whitespaces
Every C++ program contains whitespaces
Include blanks, tabs, and newline characters
Whitespaces separate special symbols, reserved words, and
identifiers
Proper utilization of whitespaces is important
Can be used to make the program more readable
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
17
‹#›
17
Data Types
A data type is set of values together with a set of allowed
operations
C++ data types fall into three categories:
Simple data type
Structured data type
Pointers
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
18
‹#›
18
Simple Data Types (1 of 2)
Three categories of simple data
Integral: integers (numbers without a decimal)
Can be further categorized: char, short, int, long, bool, unsigned
char, unsigned short, unsigned int, unsigned long
Floating-point: decimal numbers
Enumeration: a user-defined data type
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
19
‹#›
19
Simple Data Types (2 of 2)
Different compilers may allow different ranges of values
TABLE 2-2 Values and Memory Allocation for Simple Data
TypesData TypeValuesStorage (in bytes)int–147483648 (= –231
) to 2147483647 (= 231 – 1)4booltrue and false1char–128 (= –
27 ) to 127 (= 27 – 1)1long long–9223372036854775808 (–263 )
to
9223372036854775807(263 – 1)64
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
20
‹#›
20
int Data Type
Examples
-6728
0
78
+763
Positive integers do not require a + sign
A comma cannot be used within an integer
Commas are only used for separating items in a list
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
21
‹#›
21
bool Data Type
bool type
Two values: true and false
Purpose: to manipulate logical (Boolean) expressions
true and false
Logical values
bool, true, and false
Reserved words
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
22
‹#›
22
char Data Type (1 of 2)
Data type char is the smallest integral data type
It is used for single characters: letters, digits, and special
symbols
Each character is enclosed in single quotes
'A', 'a', '0', '*', '+', '$', '&'
A blank space is a character
Written ' ', with a space left between the single quotes
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
23
‹#›
23
char Data Type (2 of 2)
Different character data sets exist
ASCII: American Standard Code for Information Interchange
Each of 128 values in ASCII code set represents a different
character
Characters have a predefined ordering based on the ASCII
numeric value
Collating sequence: ordering of characters based on the
character set code
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
24
‹#›
24
Floating-Point Data Types (1 of 3)
C++ uses scientific notation to represent real numbers (floating-
point notation)
TABLE 2-3 Examples of Decimal Numbers in Scientific and
C11 Floating-Point NotationsDecimal NumberScientific
NotationC++ Floating-Point Notation75.9247.5924 *
1017.592400E10.181.8 * 10-11.800000E-10.00004534.53 * 10-
54.530000E-5–1.482-1.482 * 100-1.482000E07800.07.8 *
1037.800000E3
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
25
‹#›
25
Floating-Point Data Types (2 of 3)
float: represents any real number
Range: -3.4 * 1038 to 3.4 * 1038 (four bytes)
double: represents any real number
Range: –1.7 * 10308 to 1.7 * 10308 (eight bytes)
Minimum and maximum values of data types are system
dependent
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
26
‹#›
26
Floating-Point Data Types (3 of 3)
Maximum number of significant digits (decimal places) for float
values: 6 or 7
Maximum number of significant digits for double: 15
Precision: maximum number of significant digits
float values are called single precision
double values are called double precision
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
27
‹#›
27
Data Types, Variables, and Assignment Statements
To declare a variable, must specify its data type
Syntax rule to declare a variable is:
dataType identifier;
Examples include:
int counter;
double interestRate;
char grade;
Assignment statement has the form: variable = expression
Example: interestRate = 0.05;
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
28
‹#›
28
Arithmetic Operators, Operator Precedence, and Expressions (1
of 2)
C++ arithmetic operators include:
+ addition
- subtraction (or negation)
* multiplication
/ division
% mod (modulus or remainder)
+, -, *, and / can be used with integral and floating-point data
types
Modulus (%) can only be used with integral data types
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
29
‹#›
29
Arithmetic Operators, Operator Precedence, and Expressions (2
of 2)
When you use / with integral data types, the integral result is
truncated (no rounding)
Arithmetic expressions contain values and arithmetic operators
Operands are the numbers appearing in the expressions
Operators can be unary (one operand) or binary (two operands)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
30
‹#›
30
Order of Precedence
All operations inside () are evaluated first
*, /, and % are at the same level of precedence and are
evaluated next
+ and - have the same level of precedence and are evaluated last
When operators are on the same level
Operations are performed from left to right (associativity)
3 * 7 - 6 + 2 * 5 / 4 + 6 means
(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
31
‹#›
31
Expressions
Integral expression: all operands are integers
Yields an integral result
Example: 2 + 3 * 5
Floating-point (decimal) expression: all operands are floating-
point
Yields a floating-point result
Example: 12.8 * 17.5 - 34.50
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
32
‹#›
32
Mixed Expressions (1 of 2)
Mixed expression
Has operands of different data types
Contains integers and floating-point
Examples of mixed expressions
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
33
‹#›
33
Mixed Expressions (2 of 2)
Evaluation rules
If operator has same types of operands
The operator is evaluated according to the type of the operands
If operator has both types of operands
Integer is changed to floating-point
Operator is evaluated
Result is floating-point
Entire expression is evaluated according to precedence rules
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
34
‹#›
34
Type Conversion (Casting) (1 of 2)
Implicit type coercion: when the value of one type is
automatically changed to another type
Cast operator (also called type conversion or type casting):
provides explicit type conversion
static_cast<dataTypeName>(expression)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
35
‹#›
35
Type Conversion (Casting) (2 of 2)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
36
‹#›
36
string Type
Data type string is a programmer-defined type supplied in
ANSI/ISO Standard C++ library
A string is a sequence of zero or more characters enclosed in
double quotation marks
A null (or empty) string is a string with no characters
Each character has a relative position in the string
Position of first character is 0
The length of a string is the number of characters in it
Example: length of "William Jacob" is 13
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
37
‹#›
37
Variables, Assignment Statements, and Input Statements
Data must be loaded into main memory before it can be
manipulated
Storing data in memory is a two-step process:
Instruct the computer to allocate memory
Include statements in the program to put data into the allocated
memory
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
38
‹#›
38
Allocating Memory with Constants and Variables (1 of2)
Named constant: memory location whose content cannot change
during execution
Syntax to declare a named constant
In C++, const is a reserved word
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
39
‹#›
39
Allocating Memory with Constants and Variables (2 of 2)
Variable: memory location whose content may change during
execution
Syntax to declare one or multiple variables
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
40
‹#›
40
Putting Data into Variables
Ways to place data into a variable
Use C++’s assignment statement
Use input (read) statements
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
41
‹#›
41
Assignment Statement (1 of 4)
The assignment statement takes the form:
Expression is evaluated and its value is assigned to the variable
on the left side
A variable is said to be initialized the first time a value is
placed into it
In C++, = is called the assignment operator
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
42
‹#›
42
Assignment Statement (2 of 4)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
43
‹#›
43
Assignment Statement (3 of 4)
Example 2-14 illustrates a walk-through (tracing values through
a sequence)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
44
‹#›
44
Assignment Statement (4 of 4)
Given int variables x, y, and z. How is this legal C++ statement
evaluated?
x = y = z
The assignment operator is evaluated from right to left
The associativity of the assignment operator is from right to left
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
45
‹#›
45
Saving and Using the Value of an Expression
Declare a variable of the appropriate data type
Assign the value of the expression to the variable that was
declared
Use the assignment statement
Wherever the value of the expression is needed, use the variable
holding the value
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
46
‹#›
46
Declaring and Initializing Variables
Not all types of variables are initialized automatically
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
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
47
‹#›
47
Input (Read) Statement (1 of 3)
cin is used with >> to gather one or more inputs
This is called an input (read) statement
The stream extraction operator is >>
For example, if miles is a double variable:
cin >> miles;
Causes the computer to get a value of type double and places it
in the variable miles
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
48
‹#›
48
Input (Read) Statement (2 of 3)
Using more than one variable in cin allows more than one value
to be read at a time
Example: if feet and inches are variables of type int, this
statement:
cin >> feet >> inches;
Inputs two integers from the keyboard
Places them in variables feet and inches respectively
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
49
‹#›
49
Input (Read) Statement (3 of 3)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
50
‹#›
50
Increment and Decrement Operators
Increment operator (++): increase variable by 1
Pre-increment: ++variable
Post-increment: variable++
Decrement operator: (--) decrease variable by 1
Pre-decrement: --variable
Post-decrement: variable--
What is the difference between the following?
x = 5;
y = ++x;
x = 5;
y = x++;
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
51
‹#›
51
Output (1 of 4)
The syntax of cout and << is:
Called an output statement
The stream insertion operator is <<
Expression evaluated and its value is printed at the current
cursor position on the screen
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
52
‹#›
52
Output (2 of 4)
A manipulator is used to format the output
Example: endl causes the insertion point to move to beginning
of next line
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
53
‹#›
53
Output (3 of 4)
The new line character (new line escape sequence) is 'n'
May appear anywhere in the string
Examples
cout << "Hello there.";
cout << "My name is James.";
Output:
Hello there.My name is James.
cout << "Hello there.n";
cout << "My name is James.";
Output :
Hello there.
My name is James.
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
54
‹#›
54
Output (4 of 4)
TABLE 2-4 Commonly Used Escape SequencesEscape
SequenceDescriptionnNewlineCursor moves to the beginning of
the next linetTabCursor moves to the next tab
stopbBackspaceCursor moves one space to the
leftrReturnCursor moves to the beginning of the current line
(not the next line)BackslashBackslash is printed'Single
quotationSingle quotation mark is printed"Double
quotationDouble quotation mark is printed
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
55
‹#›
55
Preprocessor Directives (1 of 2)
C++ has a small number of operations
Many functions and symbols needed to run a C++ program are
provided as collection of libraries
Every library has a name and is referred to by a header file
Preprocessor directives are processed by the preprocessor
program
All preprocessor commands begin with #
No semicolon is placed at the end of these commands
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
56
‹#›
56
Preprocessor Directives (2 of 2)
Syntax to include a header file
For example:
#include <iostream>
Causes the preprocessor to include the header file iostream in
the program
Preprocessor commands are processed before the program goes
through the compiler
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
57
‹#›
57
namespace and Using cin and cout in a Program
cin and cout are declared in the header file iostream, but within
std namespace
To use cin and cout in a program, use the following two
statements:
#include <iostream>
using namespace std;
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
58
‹#›
58
Using the string Data Type in a Program
To use the string type, you need to access its definition from the
header file string
Include the following preprocessor directive:
#include <string>
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
59
‹#›
59
Creating a C++ Program (1 of 3)
A C++ program is a collection of functions, one of which is the
function main
The syntax of the function main used in this book has this form:
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
60
‹#›
60
Creating a C++ Program (2 of 3)
Source code is comprised of preprocessor directives and
program statements
The source code file (source file) contains the source code
The compiler generates the object code (file extension .obj)
Executable code (file extension .exe) results when object code
is linked with the system resources
The first line of the function main is called the heading of the
function:
int main()
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
61
‹#›
61
Creating a C++ Program (3 of 3)
The statements enclosed between the curly braces ({ and })
form the body of the function
A C++ program contains two types of statements:
Declaration statements declare things, such as variables
Executable statements perform calculations, manipulate data,
create output, accept input, etc.
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
62
‹#›
62
Debugging: Understanding and Fixing Syntax Errors (1 of 2)
Sample program with line numbers added on the left
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
63
‹#›
63
Debugging: Understanding and Fixing Syntax Errors (2 of 2)
Compile the program
Compiler will identify the syntax errors
The line numbers where the errors occur are specified:
ExampleCh2_Syntax_Errors.cpp
c:examplech2_syntax_errors.cpp(9): error C2146: syntax error:
missing ';' before identifier 'num'
c:examplech2_syntax_errors.cpp(11): error C2065: 'tempNum':
undeclared identifier
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
64
‹#›
64
Program Style and Form: Syntax
Syntax rules indicate what is legal and what is not legal
Errors in syntax are found in compilation
int x;//Line 1
int y//Line 2
double z;//Line 3
y = w + x;//Line 4
Compilation errors would occur at:
Line 2 (missing semicolon)
Line 4 (identifier w used but not declared)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
65
‹#›
65
Use of Blanks
In C++, you use one or more blanks to separate numbers when
data is input
Blanks are also used to separate reserved words and identifiers
from each other and from other symbols
Blanks must never appear within a reserved word or identifier
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
66
‹#›
66
Use of Semicolons, Brackets, and Commas
All C++ statements end with a semicolon
Also called a statement terminator
{ and } are not C++ statements
Can be regarded as delimiters
Commas separate items in a list
Declaring more than one variable following a data type
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
67
‹#›
67
Semantics
Semantics: set of rules that gives meaning to a language
Possible to remove all syntax errors in a program and still not
have it run
Even if it runs, it may still not do what you meant it to do
Example: 2 + 3 * 5 and (2 + 3) * 5
Both are syntactically correct expressions but have different
meanings
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
68
‹#›
68
Naming Identifiers
Identifiers can be self-documenting
CENTIMETERS_PER_INCH
Avoid run-together words
annualsale
Solution
s may include:
Capitalizing the beginning of each new word: annualSale
Inserting an underscore just before a new word: annual_sale
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
69
‹#›
69
Prompt Lines
Prompt lines: executable statements that inform the user what to
do
cout << "Please enter a number between 1 and 10 and "
<< "press the return key" << endl;
cin >> num;
Always include prompt lines when input is needed from users
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
70
‹#›
70
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
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
71
‹#›
71
Form and Style
Consider two ways of declaring variables:
Method 1
int feet, inches;
double x, y;
Method 2
int feet,inches; double x,y;
Both are correct; however, the second is harder to read
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
72
‹#›
72
More on Assignment Statements
Two forms of assignment
Simple and compound
Compound operators provide more concise notation
Compound operators: +=, -=, *=, /=, %=
Simple assignment statement example
x = x * y;
Compound assignment statement example
x *= y;
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
73
‹#›
73
Quick Review (1 of 3)
A C++ program is a collection of functions, one of which is
always called main
Identifiers consist of letters, digits, and underscores, and begin
with a letter or an underscore
The arithmetic operators in C++ are addition (+), subtraction (-
), multiplication (*), division (/), and modulus (%)
Arithmetic expressions are evaluated using the precedence
associativity rules
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
74
‹#›
74
Quick Review (2 of 3)
All operands in an integral expression are integers
All operands in a floating-point expression are decimal numbers
A mixed expression contains both integers and decimal numbers
Use the cast operator to explicitly convert values from one data
type to another
A named constant is initialized when declared
All variables must be declared before used
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
75
‹#›
75
Quick Review (3 of 3)
Use cin and the stream extraction operator >> to input from the
standard input device
Use cout and the stream insertion operator << to output to the
standard output device
Preprocessor commands are processed before the program goes
through the compiler
A file containing a C++ program usually ends with the
extension .cpp
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
76
‹#›
76
9781337117562_ppt_ch03.pptx
Chapter 3
Input/Output
C++ Programming: Program Design Including Data Structures,
Eighth Edition
‹#›
1
Objectives (1 of 2)
In this chapter, you will:
Learn what a stream is and examine input and output streams
Explore how to read data from the standard input device
Learn how to use predefined functions in a program
Explore how to use the input stream functions get, ignore,
putback, and peek
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
2
‹#›
2
Objectives (2 of 2)
Become familiar with input failure
Learn how to write data to the standard output device
Discover how to use manipulators in a program to format output
Learn how to perform input and output operations with the
string data type
Learn how to debug logic errors
Become familiar with file input and output
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
3
‹#›
3
I/O Streams and Standard I/O Devices (1 of 3)
I/O: sequence of bytes (stream of bytes) from source to
destination
Bytes are usually characters, unless program requires other
types of information
Stream: sequence of characters from the source to the
destination
Input stream: sequence of characters from an input device to the
computer
Output stream: sequence of characters from the computer to an
output device
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
4
‹#›
4
I/O Streams and Standard I/O Devices (2 of 3)
Use iostream header file to receive data from keyboard and send
output to the screen
Contains definitions of two data types:
istream: input stream
ostream: output stream
Has two variables:
cin: stands for common input
cout: stands for common output
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
5
‹#›
5
I/O Streams and Standard I/O Devices (3 of 3)
Variable declaration is similar to:
istream cin;
ostream cout;
To use cin and cout, the preprocessor directive#include
<iostream> must be used
Input stream variables: type istream
Output stream variables: type ostream
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
6
‹#›
6
cin and the Extraction Operator >> (1 of 7)
The syntax of an input statement using cin and the extraction
operator >> is
The extraction operator >> is binary
Left-side operand is an input stream variable
Example: cin
Right-side operand is a variable
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
7
‹#›
7
cin and the Extraction Operator >> (2 of 7)
No difference between a single cin with multiple variables and
multiple cin statements with one variable in each statement
cin >> payRate >> hoursWorked;
cin >> payRate;
cin >> hoursWorked;
When scanning, >> skips all whitespace
Blanks and certain nonprintable characters
>> distinguishes between character 2 and number 2 by the right-
side operand of >>
If type char or int (or double), the 2 is treated as a character or
as a number 2, respectively
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
8
‹#›
8
cin and the Extraction Operator >> (3 of 7)
TABLE 3-1 Valid Input for a Variable of the Simple Data
TypeData Type of aValid Input for acharOne printable character
except the blank.intAn integer, possibly preceded by a + or -
sign.doubleA decimal number, possibly preceded by a + or -
sign. If the actual data input is an integer, the input is converted
to a decimal number with the zero decimal part.
Entering a char value into an int or double variable causes
serious errors, called input failure
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
9
‹#›
9
cin and the Extraction Operator >> (4 of 7)
When reading data into a char variable
>> skips leading whitespace, finds and stores only the next
character
Reading stops after a single character
To read data into an int or double variable
>> skips leading whitespace, reads + or - sign (if any), reads the
digits (including decimal for floating-point variables)
Reading stops on whitespace or a non-digit character
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
10
‹#›
10
cin and the Extraction Operator >> (5 of 7)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
11
‹#›
11
cin and the Extraction Operator >> (6 of 7)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
12
‹#›
12
cin and the Extraction Operator >> (7 of 7)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
13
‹#›
13
Using Predefined Functions in a Program (1 of 3)
A function (subprogram) is a set of instructions
When activated, it accomplishes a task
main executes when a program is run
Other functions execute only when called
C++ includes a wealth of functions
Predefined functions are organized as a collection of libraries
called header files
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
14
‹#›
14
Using Predefined Functions in a Program (2 of 3)
Header file may contain several functions
To use a predefined function, you need the name of the
appropriate header file
You also need to know:
Function name
Number of parameters required
Type of each parameter
What the function is going to do
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
15
‹#›
15
Using Predefined Functions in a Program (3 of 3)
To use pow (power), include cmath
Two numeric parameters
Syntax: pow(x,y) = xy
x and y are the arguments or parameters
In pow(2,3), the parameters are 2 and 3
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
16
‹#›
16
cin and the get Function
The get function
Inputs next character (including whitespace)
Stores in memory location indicated by its argument
The syntax of cin and the get function
varChar is a char variable
It is the argument (or parameter) of the function
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
17
‹#›
17
cin and the ignore Function (1 of 2)
ignore function
Discards a portion of the input
The syntax to use the function ignore is:
intExp is an integer expression
chExp is a char expression
If intExp is a value m, the statement says to ignore the next m
characters or all characters until the character specified by
chExp
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
18
‹#›
18
cin and the ignore Function (2 of 2)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
19
‹#›
19
The putback and peek Functions (1 of 2)
putback function
Places previous character extracted by the get function from an
input stream back to that stream
peek function
Returns next character from the input stream
Does not remove the character from that stream
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
20
‹#›
20
The putback and peek Functions (2 of 2)
Syntax for putback
istreamVar: an input stream variable (such as cin)
ch is a char variable
Syntax for peek
istreamVar: an input stream variable (such as cin)
ch is a char variable
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
21
‹#›
21
The Dot Notation between I/O Stream Variables and I/O
Functions: A Precaution
In the statement
cin.get(ch);
cin and get are two separate identifiers separated by a dot
Called the dot notation, the dot separates the input stream
variable name from the member, or function, name
In C++, the dot is the member access operator
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
22
‹#›
22
Input Failure
Things can go wrong during execution
If input data does not match corresponding variables, the
program may run into problems
Trying to read a letter into an int or double variable will result
in an input failure
If an error occurs when reading data
Input stream enters the fail state
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
23
‹#›
23
The clear Function
Once in a fail state, all further I/O statements using that stream
are ignored
The program continues to execute with whatever values are
stored in variables
This causes incorrect results
The clear function restores the input stream to a working state
The syntax of the function clear is:
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
24
‹#›
24
Output and Formatting Output
Syntax of cout when used with <<
expression is evaluated
value is printed
manipulator is used to format the output
Example: endl
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
25
‹#›
25
setprecision Manipulator
Syntax
Outputs decimal numbers with up to n decimal places
Must include the header file iomanip
#include <iomanip>
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
26
‹#›
26
fixed Manipulator
fixed outputs floating-point numbers in a fixed decimal format
Example: cout << fixed;
Disable by using the stream member function unsetf
Example: cout.unsetf(ios::fixed);
scientific manipulator outputs floating-point numbers in
scientific format
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
27
‹#›
27
showpoint Manipulator
showpoint forces output to show the decimal point and trailing
zeros
Examples
cout << showpoint;
cout << fixed << showpoint;
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
28
‹#›
28
C++14 Digit Separator
Reading and writing of long numbers can be error prone
In C++, commas cannot be used to separate the digits of a
number
C++14 introduces digit separator ' (single-quote character)
Example: 87523872918 can be represented as 87'523'872'918
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
29
‹#›
29
setw
Outputs the value of an expression in a specified number of
columns
cout << setw(5) << x << endl;
If number of columns exceeds the number of columns required
by the expression
Output of the expression is right-justified
Unused columns to the left are filled with spaces
Must include the header file iomanip
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
30
‹#›
30
Additional Output Formatting Tools
Additional formatting tools that give you more control over
your output:
setfill manipulator
left and right manipulators
unsetf manipulator
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
31
‹#›
31
setfill Manipulator
Output stream variables can use setfill to fill unused columns
with a character
Example:
cout << setfill('#');
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
32
‹#›
32
left and right Manipulators
left manipulator left-justifies the output
Disable left by using unsetf
right manipulator right-justifies the output
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
33
‹#›
33
Types of Manipulators
Two types of manipulators
Those with parameters
Those without parameters
Parameterized stream manipulators require the iomanip header
setprecision, setw, and setfill
Manipulators without parameters require the iostream header
endl, fixed, scientific, showpoint, and left
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
34
‹#›
34
Input/Output and the string Type
An input stream variable (such as cin) and >> operator can read
a string into a variable of the data type string
The extraction operator:
Skips any leading whitespace characters
Stops reading at a whitespace character
The function getline reads until end of the current line
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
35
‹#›
35
Debugging: Understanding Logic Errors and Debugging with
cout statements
Syntax errors are reported by the compiler
Logic errors are typically not caught by the compiler
Spot and correct using cout statements
Temporarily insert an output statement
Correct the problem
Remove output statement
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
36
‹#›
36
File Input/Output
A file is an area in secondary storage to hold info
File I/O is a five-step process
Include fstream header
Declare file stream variables
Associate the file stream variables with the input/output sources
– referred to as opening the files
Use the file stream variables with >>, <<, or other input/output
functions
Close the files
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
37
‹#›
37
Quick Review (1 of 3)
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
cin: common input
cout: common output
To use cin and cout, include iostream header
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
38
‹#›
38
Quick Review (2 of 3)
get reads data character-by-character
ignore skips data in a line
putback puts last character retrieved by get back to the input
stream
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
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
39
‹#›
39
Quick Review (3 of 3)
The manipulators setprecision, fixed, showpoint, setw, setfill,
left, and right can be used for formatting output
Include iomanip for the manipulators setprecision, setw, and
setfill
Header fstream contains the definitions of ifstream and ofstream
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
40
‹#›
40
9781337117562_ppt_ch04.pptx
Chapter 4
Control Structures I (Selection)
C++ Programming: Program Design Including Data Structures,
Eighth Edition
‹#›
1
Objectives (1 of 2)
In this chapter, you will:
Learn about control structures
Examine relational operators
Discover how to use the selection control structures if, if…else
Examine int and bool data types and logical (Boolean)
expressions
Examine logical operators
Explore how to form and evaluate logical (Boolean) expressions
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
2
Objectives (2 of 2)
Learn how relational operators work with the string type
Become aware of short-circuit evaluation
Learn how the conditional operator, ?:, works
Learn how to use pseudocode to develop, test, and debug a
program
Discover how to use a switch statement in a program
Learn how to avoid bugs by avoiding partially understood
concepts
Learn how to use the assert function to terminate a program
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
3
Control Structures (1 of 2)
A computer can proceed:
In sequence
Selectively (branch): making a choice
Repetitively: looping
By calling a function
The two most common control structures are:
Selection
Repetition
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
4
Control Structures (2 of 2)
FIGURE 4-1 Flow of execution
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
5
Selection: if and if...else
An expression that evaluates to true or false is called a logical
expression
“8 is greater than 3” is true
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
6
Relational Operators
TABLE 4-1 Relational Operators in
C++OperatorDescription==equal to!=not equal to<less
than<=less than or equal to>greater than>=greater than or equal
to
Each relational operator is a binary operator (requires two
operands)
Expressions using these operators always evaluate to true or
false
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
Relational Operators and Simple Data Types
You can use the relational operators with all three simple data
types
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
8
Comparing Characters
In an expression of char values using relational operators:
The result depends on the machine’s collating sequence
ASCII character set
Logical (Boolean) expressions:
Include expressions such as 4 < 6 and 'R' > 'T’
Return an integer value of 1 if the logical expression evaluates
to true
Return an integer value of 0 otherwise
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
9
One-Way Selection (1 of 2)
One-way selection syntax
The statement is:
Executed if the value of the expression is true
Bypassed if the value is false; program goes to the next
statement
The expression is also called a decision maker
The statement following the expression is also called the action
statement
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
10
One-Way Selection (2 of 2)
FIGURE 4-2 One-way selection
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
11
Two-Way Selection (1 of 2)
Two-way selection syntax
If expression is true, statement1 is executed; otherwise,
statement2 is executed
statement1 and statement2 are any C++ statements
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
12
Two-Way Selection (2 of 2)
FIGURE 4-3 Two-way selection
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
13
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
Logical expression value was stored in a variable of the data
type int
You can use the int data type to manipulate logical (Boolean)
expressions
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
14
bool Data Type and Logical (Boolean) Expressions
The data type bool has logical (Boolean) values true and false
bool, true, and false are reserved words
The identifier true has the value 1
The identifier false has the value 0
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
15
Logical (Boolean) Operators and Logical Expressions (1 of 5)
Logical (Boolean) operators enable you to combine logical
expressions
TABLE 4-2 Logical (Boolean) Operators in
C++OperatorDescription!not&&and||or
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
16
Logical (Boolean) Operators and Logical Expressions (2 of 5)
TABLE 4-3 The ! (Not) OperatorExpression!(Expression)true
(nonzero)false (0)false (0)true (1)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
17
Logical (Boolean) Operators and Logical Expressions (3 of 5)
TABLE 4-4 The && (And)
OperatorExpression1Expression2Expression1 &&
Expression2true (nonzero)true (nonzero)true (1)true
(nonzero)false (0)false (0)false (0)true (nonzero)false (0)false
(0)false (0)false (0)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
18
Logical (Boolean) Operators and Logical Expressions (4 of 5)
TABLE 4-5 The || (Or)
OperatorExpression1Expression2Expression1 || Expression2true
(nonzero)true (nonzero)true (1)true (nonzero)false (0)true
(1)false (0)true (nonzero)true (1)false (0)false (0)false (0)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
19
Logical (Boolean) Operators and Logical Expressions (5 of 5)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
Order of Precedence (1 of 5)
Relational and logical operators are evaluated from left to right
The associativity is left to right
Parentheses can override precedence
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
21
Order of Precedence (2 of 5)
TABLE 4-6 Precedence of OperatorsOperatorsPrecedence!, +, -
(unary operators)first*, /, %second+, -third<, <=, >=,
>fourth==, !=fifth&&sixth||seventh= (assignment operator)last
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
22
Order of Precedence (3 of 5)
© 2018 Cengage Learning. All Rights Reserved. May not be
copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product
or service or otherwise on a password-protected website for
classroom
‹#›
23
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx

More Related Content

Similar to 9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx

Chapter 03.ppt
Chapter 03.pptChapter 03.ppt
Chapter 03.ppt
anisur_rehman
 
Chapter 9 Client and application Security
Chapter 9 Client and application SecurityChapter 9 Client and application Security
Chapter 9 Client and application Security
Dr. Ahmed Al Zaidy
 
Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
DuncanWachira3
 
Kubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad Assis
Kubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad AssisKubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad Assis
Kubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad Assis
AgileSparks
 
1WebDesign6EChapter1TheEnvironmentandtheTools.docx
1WebDesign6EChapter1TheEnvironmentandtheTools.docx1WebDesign6EChapter1TheEnvironmentandtheTools.docx
1WebDesign6EChapter1TheEnvironmentandtheTools.docx
lorainedeserre
 
Intel Technologies for High Performance Computing
Intel Technologies for High Performance ComputingIntel Technologies for High Performance Computing
Intel Technologies for High Performance Computing
Intel Software Brasil
 
Intro to Web Design 6e Chapter 1
Intro to Web Design 6e Chapter 1Intro to Web Design 6e Chapter 1
Intro to Web Design 6e Chapter 1
Steve Guinan
 
What are latest new features that DPDK brings into 2018?
What are latest new features that DPDK brings into 2018?What are latest new features that DPDK brings into 2018?
What are latest new features that DPDK brings into 2018?
Michelle Holley
 
Embedded Software Design
Embedded Software DesignEmbedded Software Design
Embedded Software Design
Anil Kumar Pugalia
 
NVMe and Flash – Make Your Storage Great Again!
NVMe and Flash – Make Your Storage Great Again!NVMe and Flash – Make Your Storage Great Again!
NVMe and Flash – Make Your Storage Great Again!
DataCore Software
 
Light-weighted HDFS disaster recovery
Light-weighted HDFS disaster recoveryLight-weighted HDFS disaster recovery
Light-weighted HDFS disaster recovery
DataWorks Summit
 
Catching the Software Defined Storage Wave
Catching the Software Defined Storage WaveCatching the Software Defined Storage Wave
Catching the Software Defined Storage Wave
DataCore Software
 
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon Web Services
 
BSC LMS DDL
BSC LMS DDL BSC LMS DDL
BSC LMS DDL
Ganesan Narayanasamy
 
DC16_Ch06 (1).pptx
DC16_Ch06 (1).pptxDC16_Ch06 (1).pptx
DC16_Ch06 (1).pptx
Aiman Niazi
 
Enabling a hardware accelerated deep learning data science experience for Apa...
Enabling a hardware accelerated deep learning data science experience for Apa...Enabling a hardware accelerated deep learning data science experience for Apa...
Enabling a hardware accelerated deep learning data science experience for Apa...
DataWorks Summit
 
Chapter 10 Mobile and Embedded Device Security
Chapter 10 Mobile and Embedded Device Security Chapter 10 Mobile and Embedded Device Security
Chapter 10 Mobile and Embedded Device Security
Dr. Ahmed Al Zaidy
 
Chapter 14 Business Continuity
Chapter 14 Business ContinuityChapter 14 Business Continuity
Chapter 14 Business Continuity
Dr. Ahmed Al Zaidy
 
The Role of Standards in IoT Security
The Role of Standards in IoT SecurityThe Role of Standards in IoT Security
The Role of Standards in IoT Security
Hannes Tschofenig
 
Predicting Startup Market Trends based on the news and social media - Albert ...
Predicting Startup Market Trends based on the news and social media - Albert ...Predicting Startup Market Trends based on the news and social media - Albert ...
Predicting Startup Market Trends based on the news and social media - Albert ...
GetInData
 

Similar to 9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx (20)

Chapter 03.ppt
Chapter 03.pptChapter 03.ppt
Chapter 03.ppt
 
Chapter 9 Client and application Security
Chapter 9 Client and application SecurityChapter 9 Client and application Security
Chapter 9 Client and application Security
 
Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
 
Kubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad Assis
Kubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad AssisKubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad Assis
Kubernetes is Hard! Lessons Learned Taking Our Apps to Kubernetes by Eldad Assis
 
1WebDesign6EChapter1TheEnvironmentandtheTools.docx
1WebDesign6EChapter1TheEnvironmentandtheTools.docx1WebDesign6EChapter1TheEnvironmentandtheTools.docx
1WebDesign6EChapter1TheEnvironmentandtheTools.docx
 
Intel Technologies for High Performance Computing
Intel Technologies for High Performance ComputingIntel Technologies for High Performance Computing
Intel Technologies for High Performance Computing
 
Intro to Web Design 6e Chapter 1
Intro to Web Design 6e Chapter 1Intro to Web Design 6e Chapter 1
Intro to Web Design 6e Chapter 1
 
What are latest new features that DPDK brings into 2018?
What are latest new features that DPDK brings into 2018?What are latest new features that DPDK brings into 2018?
What are latest new features that DPDK brings into 2018?
 
Embedded Software Design
Embedded Software DesignEmbedded Software Design
Embedded Software Design
 
NVMe and Flash – Make Your Storage Great Again!
NVMe and Flash – Make Your Storage Great Again!NVMe and Flash – Make Your Storage Great Again!
NVMe and Flash – Make Your Storage Great Again!
 
Light-weighted HDFS disaster recovery
Light-weighted HDFS disaster recoveryLight-weighted HDFS disaster recovery
Light-weighted HDFS disaster recovery
 
Catching the Software Defined Storage Wave
Catching the Software Defined Storage WaveCatching the Software Defined Storage Wave
Catching the Software Defined Storage Wave
 
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
 
BSC LMS DDL
BSC LMS DDL BSC LMS DDL
BSC LMS DDL
 
DC16_Ch06 (1).pptx
DC16_Ch06 (1).pptxDC16_Ch06 (1).pptx
DC16_Ch06 (1).pptx
 
Enabling a hardware accelerated deep learning data science experience for Apa...
Enabling a hardware accelerated deep learning data science experience for Apa...Enabling a hardware accelerated deep learning data science experience for Apa...
Enabling a hardware accelerated deep learning data science experience for Apa...
 
Chapter 10 Mobile and Embedded Device Security
Chapter 10 Mobile and Embedded Device Security Chapter 10 Mobile and Embedded Device Security
Chapter 10 Mobile and Embedded Device Security
 
Chapter 14 Business Continuity
Chapter 14 Business ContinuityChapter 14 Business Continuity
Chapter 14 Business Continuity
 
The Role of Standards in IoT Security
The Role of Standards in IoT SecurityThe Role of Standards in IoT Security
The Role of Standards in IoT Security
 
Predicting Startup Market Trends based on the news and social media - Albert ...
Predicting Startup Market Trends based on the news and social media - Albert ...Predicting Startup Market Trends based on the news and social media - Albert ...
Predicting Startup Market Trends based on the news and social media - Albert ...
 

More from sleeperharwell

For this assignment, review the articleAbomhara, M., & Koie.docx
For this assignment, review the articleAbomhara, M., & Koie.docxFor this assignment, review the articleAbomhara, M., & Koie.docx
For this assignment, review the articleAbomhara, M., & Koie.docx
sleeperharwell
 
For this assignment, provide your perspective about Privacy versus N.docx
For this assignment, provide your perspective about Privacy versus N.docxFor this assignment, provide your perspective about Privacy versus N.docx
For this assignment, provide your perspective about Privacy versus N.docx
sleeperharwell
 
For this assignment, provide your perspective about Privacy vers.docx
For this assignment, provide your perspective about Privacy vers.docxFor this assignment, provide your perspective about Privacy vers.docx
For this assignment, provide your perspective about Privacy vers.docx
sleeperharwell
 
For this Assignment, read the case study for Claudia and find two to.docx
For this Assignment, read the case study for Claudia and find two to.docxFor this Assignment, read the case study for Claudia and find two to.docx
For this Assignment, read the case study for Claudia and find two to.docx
sleeperharwell
 
For this assignment, please start by doing research regarding the se.docx
For this assignment, please start by doing research regarding the se.docxFor this assignment, please start by doing research regarding the se.docx
For this assignment, please start by doing research regarding the se.docx
sleeperharwell
 
For this assignment, please discuss the following questionsWh.docx
For this assignment, please discuss the following questionsWh.docxFor this assignment, please discuss the following questionsWh.docx
For this assignment, please discuss the following questionsWh.docx
sleeperharwell
 
For this assignment, locate a news article about an organization.docx
For this assignment, locate a news article about an organization.docxFor this assignment, locate a news article about an organization.docx
For this assignment, locate a news article about an organization.docx
sleeperharwell
 
For this assignment, it requires you Identifies the historic conte.docx
For this assignment, it requires you Identifies the historic conte.docxFor this assignment, it requires you Identifies the historic conte.docx
For this assignment, it requires you Identifies the historic conte.docx
sleeperharwell
 
For this assignment, create a framework from which an international .docx
For this assignment, create a framework from which an international .docxFor this assignment, create a framework from which an international .docx
For this assignment, create a framework from which an international .docx
sleeperharwell
 
For this assignment, create a 15-20 slide digital presentation in tw.docx
For this assignment, create a 15-20 slide digital presentation in tw.docxFor this assignment, create a 15-20 slide digital presentation in tw.docx
For this assignment, create a 15-20 slide digital presentation in tw.docx
sleeperharwell
 
For this assignment, you are to complete aclinical case - narrat.docx
For this assignment, you are to complete aclinical case - narrat.docxFor this assignment, you are to complete aclinical case - narrat.docx
For this assignment, you are to complete aclinical case - narrat.docx
sleeperharwell
 
For this assignment, you are to complete aclinical case - narr.docx
For this assignment, you are to complete aclinical case - narr.docxFor this assignment, you are to complete aclinical case - narr.docx
For this assignment, you are to complete aclinical case - narr.docx
sleeperharwell
 
For this assignment, you are provided with four video case studies (.docx
For this assignment, you are provided with four video case studies (.docxFor this assignment, you are provided with four video case studies (.docx
For this assignment, you are provided with four video case studies (.docx
sleeperharwell
 
For this assignment, you are going to tell a story, but not just.docx
For this assignment, you are going to tell a story, but not just.docxFor this assignment, you are going to tell a story, but not just.docx
For this assignment, you are going to tell a story, but not just.docx
sleeperharwell
 
For this assignment, you are asked to prepare a Reflection Paper. Af.docx
For this assignment, you are asked to prepare a Reflection Paper. Af.docxFor this assignment, you are asked to prepare a Reflection Paper. Af.docx
For this assignment, you are asked to prepare a Reflection Paper. Af.docx
sleeperharwell
 
For this assignment, you are asked to prepare a Reflection Paper. .docx
For this assignment, you are asked to prepare a Reflection Paper. .docxFor this assignment, you are asked to prepare a Reflection Paper. .docx
For this assignment, you are asked to prepare a Reflection Paper. .docx
sleeperharwell
 
For this assignment, you are asked to conduct some Internet research.docx
For this assignment, you are asked to conduct some Internet research.docxFor this assignment, you are asked to conduct some Internet research.docx
For this assignment, you are asked to conduct some Internet research.docx
sleeperharwell
 
For this assignment, you are a professor teaching a graduate-level p.docx
For this assignment, you are a professor teaching a graduate-level p.docxFor this assignment, you are a professor teaching a graduate-level p.docx
For this assignment, you are a professor teaching a graduate-level p.docx
sleeperharwell
 
For this assignment, we will be visiting the PBS website,Race  .docx
For this assignment, we will be visiting the PBS website,Race  .docxFor this assignment, we will be visiting the PBS website,Race  .docx
For this assignment, we will be visiting the PBS website,Race  .docx
sleeperharwell
 
For this assignment, the student starts the project by identifying a.docx
For this assignment, the student starts the project by identifying a.docxFor this assignment, the student starts the project by identifying a.docx
For this assignment, the student starts the project by identifying a.docx
sleeperharwell
 

More from sleeperharwell (20)

For this assignment, review the articleAbomhara, M., & Koie.docx
For this assignment, review the articleAbomhara, M., & Koie.docxFor this assignment, review the articleAbomhara, M., & Koie.docx
For this assignment, review the articleAbomhara, M., & Koie.docx
 
For this assignment, provide your perspective about Privacy versus N.docx
For this assignment, provide your perspective about Privacy versus N.docxFor this assignment, provide your perspective about Privacy versus N.docx
For this assignment, provide your perspective about Privacy versus N.docx
 
For this assignment, provide your perspective about Privacy vers.docx
For this assignment, provide your perspective about Privacy vers.docxFor this assignment, provide your perspective about Privacy vers.docx
For this assignment, provide your perspective about Privacy vers.docx
 
For this Assignment, read the case study for Claudia and find two to.docx
For this Assignment, read the case study for Claudia and find two to.docxFor this Assignment, read the case study for Claudia and find two to.docx
For this Assignment, read the case study for Claudia and find two to.docx
 
For this assignment, please start by doing research regarding the se.docx
For this assignment, please start by doing research regarding the se.docxFor this assignment, please start by doing research regarding the se.docx
For this assignment, please start by doing research regarding the se.docx
 
For this assignment, please discuss the following questionsWh.docx
For this assignment, please discuss the following questionsWh.docxFor this assignment, please discuss the following questionsWh.docx
For this assignment, please discuss the following questionsWh.docx
 
For this assignment, locate a news article about an organization.docx
For this assignment, locate a news article about an organization.docxFor this assignment, locate a news article about an organization.docx
For this assignment, locate a news article about an organization.docx
 
For this assignment, it requires you Identifies the historic conte.docx
For this assignment, it requires you Identifies the historic conte.docxFor this assignment, it requires you Identifies the historic conte.docx
For this assignment, it requires you Identifies the historic conte.docx
 
For this assignment, create a framework from which an international .docx
For this assignment, create a framework from which an international .docxFor this assignment, create a framework from which an international .docx
For this assignment, create a framework from which an international .docx
 
For this assignment, create a 15-20 slide digital presentation in tw.docx
For this assignment, create a 15-20 slide digital presentation in tw.docxFor this assignment, create a 15-20 slide digital presentation in tw.docx
For this assignment, create a 15-20 slide digital presentation in tw.docx
 
For this assignment, you are to complete aclinical case - narrat.docx
For this assignment, you are to complete aclinical case - narrat.docxFor this assignment, you are to complete aclinical case - narrat.docx
For this assignment, you are to complete aclinical case - narrat.docx
 
For this assignment, you are to complete aclinical case - narr.docx
For this assignment, you are to complete aclinical case - narr.docxFor this assignment, you are to complete aclinical case - narr.docx
For this assignment, you are to complete aclinical case - narr.docx
 
For this assignment, you are provided with four video case studies (.docx
For this assignment, you are provided with four video case studies (.docxFor this assignment, you are provided with four video case studies (.docx
For this assignment, you are provided with four video case studies (.docx
 
For this assignment, you are going to tell a story, but not just.docx
For this assignment, you are going to tell a story, but not just.docxFor this assignment, you are going to tell a story, but not just.docx
For this assignment, you are going to tell a story, but not just.docx
 
For this assignment, you are asked to prepare a Reflection Paper. Af.docx
For this assignment, you are asked to prepare a Reflection Paper. Af.docxFor this assignment, you are asked to prepare a Reflection Paper. Af.docx
For this assignment, you are asked to prepare a Reflection Paper. Af.docx
 
For this assignment, you are asked to prepare a Reflection Paper. .docx
For this assignment, you are asked to prepare a Reflection Paper. .docxFor this assignment, you are asked to prepare a Reflection Paper. .docx
For this assignment, you are asked to prepare a Reflection Paper. .docx
 
For this assignment, you are asked to conduct some Internet research.docx
For this assignment, you are asked to conduct some Internet research.docxFor this assignment, you are asked to conduct some Internet research.docx
For this assignment, you are asked to conduct some Internet research.docx
 
For this assignment, you are a professor teaching a graduate-level p.docx
For this assignment, you are a professor teaching a graduate-level p.docxFor this assignment, you are a professor teaching a graduate-level p.docx
For this assignment, you are a professor teaching a graduate-level p.docx
 
For this assignment, we will be visiting the PBS website,Race  .docx
For this assignment, we will be visiting the PBS website,Race  .docxFor this assignment, we will be visiting the PBS website,Race  .docx
For this assignment, we will be visiting the PBS website,Race  .docx
 
For this assignment, the student starts the project by identifying a.docx
For this assignment, the student starts the project by identifying a.docxFor this assignment, the student starts the project by identifying a.docx
For this assignment, the student starts the project by identifying a.docx
 

Recently uploaded

The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 

Recently uploaded (20)

The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 

9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx

  • 1. 9781337117562_ppt_ch01.pptx Chapter 1 An Overview of Computers and Programming Languages © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. C++ Programming: Program Design Including Data Structures, Eighth Edition ‹#› Objectives (1 of 2) In this chapter, you will: Learn about different types of computers Explore the hardware and software components of a computer system Learn about the language of a computer Learn about the evolution of programming languages Examine high-level programming languages Discover what a compiler is and what it does © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#›
  • 2. Objectives (2 of 2) Examine a C++ program Explore how a C++ program is processed Learn what an algorithm is and explore problem-solving techniques Become aware of structured design and object-oriented design programming methodologies Become aware of Standard C++, ANSI/ISO Standard C++, C++11, and C++14 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› Introduction Without software, a computer is useless Software is developed with programming languages C++ is a programming language C++ is suited for a wide variety of programming tasks © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 4
  • 3. A Brief Overview of the History of Computers (1 of 3) Early calculation devices Abacus Pascaline Leibniz device Jacquard’s weaving looms Babbage machines: difference and analytic engines Hollerith machine © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 5 A Brief Overview of the History of Computers (2 of 3) Early computer-like machines Mark I Electronic Numerical Integrator and Calculator (ENIAC) Von Neumann architecture Universal Automatic Computer (UNIVAC) Transistors and microprocessors © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#›
  • 4. 6 A Brief Overview of the History of Computers (3 of 3) Categories of computers Mainframe computers Midsize computers Micro computers (personal computers) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 7 Elements of a Computer System Two main components Hardware Software © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 8 Hardware Central processing unit (CPU)
  • 5. Main memory (MM) or random access memory (RAM) Secondary storage Input/output devices © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 9 Central Processing Unit and Main Memory (1 of 4) Central processing unit Brain of the computer Most expensive piece of hardware Operations Carries out arithmetic and logical operations © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 10 Central Processing Unit and Main Memory (2 of 4) FIGURE 1-1 Hardware components of a computer and main memory © 2018 Cengage Learning. All Rights Reserved. May not be
  • 6. copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 11 Central Processing Unit and Main Memory (3 of 4) Random access memory (or main memory) is directly connected to the CPU All programs must be loaded into main memory before they can be executed All data must be brought into main memory before it can be manipulated When computer power is turned off, everything in main memory is lost © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 12 Central Processing Unit and Main Memory (4 of 4) Main memory is an ordered sequence of memory cells Each cell has a unique location in main memory, called the address of the cell Each cell can contain either a programming instruction or data © 2018 Cengage Learning. All Rights Reserved. May not be
  • 7. copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 13 Secondary Storage Secondary storage: device that stores information permanently Examples of secondary storage Hard disks Flash drives CD-ROMs © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 14 Input/Output Devices Input devices feed data and programs into computers Keyboard Mouse Scanner Camera Secondary storage Output devices display results Monitor
  • 8. Printer Secondary storage © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 15 Software Software are programs written to perform specific tasks System programs control the computer Operating system monitors the overall activity of the computer and provides services such as: Memory management Input/output activities Storage management Application programs perform a specific task Word processors Spreadsheets Games © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 16
  • 9. The Language of a Computer (1 of 4) Analog signals: continuously varying continuous wave forms Digital signals: sequences of 0s and 1s Machine language: language of a computer A sequence of 0s and 1s Binary digit (bit): the digit 0 or 1 Binary code (binary number): a sequence of 0s and 1s © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 17 The Language of a Computer (2 of 4) Byte: a sequence of eight bits Kilobyte (KB): 210 bytes = 1024 bytes ASCII (American Standard Code for Information Interchange) 128 characters A is encoded as 1000001 (66th character) The character 3 is encoded as 0110011 (51st character) Number systems The decimal system (base 10) is used in our daily life The computer uses the binary (or base 2) number system © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#›
  • 10. 18 The Language of a Computer (3 of 4) TABLE 1-1 Binary Units UnitSymbolBits/BytesByte8 bitsKilobyteKB210 bytes = 1024 bytesMegabyteMB1024 KB = 210 KB = 220 bytes = 1,048,576 bytesGigabyteGB1024MB = 210 MB = 230 bytes = 1,073,741,824 bytesTerabyteTB1024 GB = 210 GB = 240 bytes = 1,099,511,627,776 bytesPetabytePB1024 TB = 210 TB = 250 bytes = 1,125,899,906,842,624 bytesExabyteEB1024 PB = 210 PB = 260 bytes = 1,152,921,504,606,846,976 bytesZettabyteZB1024 EB5 210 EB = 270 bytes = 1,180,591,620,717,411,303,424 bytes © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› The Language of a Computer (4 of 4) Unicode is another coding scheme 65,536 characters Two bytes (16 bits) to store a character © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 20
  • 11. The Evolution of Programming Languages (1 of 3) Early computers were programmed in machine language To calculate wages = rate * hours in machine language: 100100 010001 //Load 100110 010010 //Multiply 100010 010011 //Store © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 21 The Evolution of Programming Languages (2 of 3) Assembly language instructions are mnemonic Instructions are written in an easy-to-remember form An assembler translates a program written in assembly language into machine language Using assembly language instructions, wages = rate * hours can be written as: LOAD rate MULT hours STOR wages © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#›
  • 12. 22 The Evolution of Programming Languages (3 of 3) High-level languages include Basic, FORTRAN, COBOL, C, C++, C#, Java, and Python Compiler: translates a program written in a high-level language into machine language In C++, the weekly wages equation can be written as: wages = rate * hours; © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 23 Processing a C++ Program (1 of 4) #include <iostream> using namespace std; int main() { cout << "My first C++ program." << endl; return 0; } Sample Run: My first C++ program. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 13. classroom use. ‹#› 24 Processing a C++ Program (2 of 4) Steps needed to process a C++ program Use a text editor to create the source code (source program) in C++ Include preprocessor directives Begin with the symbol # and are processed by the preprocessor Use the compiler to: Check that the program obeys the language rules Translate the program into machine language (object program) Use an integrated development environment (IDE) to develop programs in a high-level language Programs such as mathematical functions are available The library contains prewritten code you can use A linker combines object program with other programs in the library to create executable code The loader loads executable program into main memory The last step is to execute the program © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 25
  • 14. Processing a C++ Program (3 of 4) IDEs are quite user friendly Compiler identifies the syntax errors and also suggests how to correct them Build or Rebuild is a simple command that links the object code with the resources used from the IDE © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 26 Processing a C++ Program (4 of 4) FIGURE 1-2 Processing a C++ program © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 27 Programming with the Problem Analysis–Coding–Execution Cycle Programming is a process of problem solving An algorithm is a step-by-step problem-solving process A solution is achieved in a finite amount of time
  • 15. FIGURE 1-3 Problem analysis–coding–execution cycle © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 28 The Problem Analysis–Coding–Execution Cycle (1 of 5) Step 1: Analyze the problem Outline the problem and its requirements Design steps (algorithm) to solve the problem Step 2: Implement the algorithm Implement the algorithm in code Verify that the algorithm works Step 3: Maintain the program Use and modify the program if the problem domain changes © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 29 The Problem Analysis–Coding–Execution Cycle (2 of 5) Analyze the problem using these steps: Step 1: Thoroughly understand the problem and all requirements
  • 16. Step 2: Understand the problem requirements Does program require user interaction? Does program manipulate data? What is the output? Step 3: If complex, divide the problem into subproblems Analyze and design algorithms for each subproblem Check the correctness of algorithm Test the algorithm using sample data Some mathematical analysis might be required © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 30 The Problem Analysis–Coding–Execution Cycle (3 of 5) Once the algorithm is designed and correctness is verified Write the equivalent code in high-level language Enter the program using a text editor © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 31 The Problem Analysis–Coding–Execution Cycle (4 of 5)
  • 17. Run code through the compiler If compiler generates errors Look at code and remove errors Run code again through compiler If there are no syntax errors Compiler generates equivalent machine code Link machine code with the system’s resources Performed by the linker © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 32 The Problem Analysis–Coding–Execution Cycle (5 of 5) Once compiled and linked, the loader can place program into main memory for execution The final step is to execute the program Compiler guarantees that the program follows the rules of the language Does not guarantee that the program will run correctly © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 33
  • 18. Example 1-1 (1 of 2) Design an algorithm to find the perimeter and area of a rectangle The perimeter and area of the rectangle are given by the following formulas: perimeter = 2 * (length + width) area = length * width © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 34 Example 1-1 (2 of 2) Algorithm Get the length of the rectangle Get the width of the rectangle Find the perimeter with this equation: perimeter = 2 * (length + width) Find the area with this equation: area = length * width © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#›
  • 19. 35 Example 1-5 (1 of 4) Calculate each student’s grade There are 10 students in a class Each student has taken five tests Each test is worth 100 points Design algorithms to: Calculate the grade for each student and class average Find the average test score Determine the grade Use the provided data: students’ names and test scores © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 36 Example 1-5 (2 of 4) Algorithm to determine the average test score Get the five test scores Add the five test scores The sum of the test scores is represented by sum Suppose average stands for the average test score: average = sum / 5; © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
  • 20. ‹#› 37 Example 1-5 (3 of 4) Algorithm to determine the grade: if average is greater than or equal to 90 grade = A otherwise if average is greater than or equal to 80 and less than 90 grade = B otherwise if average is greater than or equal to 70 and less than 80 grade = C otherwise if average is greater than or equal to 60 and less than 70 grade = D otherwise grade = F © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 38 Example 1-5 (4 of 4) Main algorithm is presented below: totalAverage = 0; Repeat the following for each student: Get student’s name
  • 21. Use the algorithm to find the average test score Use the algorithm to find the grade Update totalAverage by adding current student’s average test score Determine the class average as follows: classAverage = totalAverage / 10 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 39 Programming Methodologies Two popular approaches to programming design Structured Object-oriented © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 40 Structured Programming Structured design Involves dividing a problem into smaller subproblems Structured programming
  • 22. Involves implementing a structured design The structured design approach is also called: Top-down (or bottom-up) design Stepwise refinement Modular programming © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 41 Object-Oriented Programming (1 of 3) Object-oriented design (OOD) Identify components called objects Determine how objects interact with each other Specify relevant data and possible operations to be performed on that data Each object consists of data and operations on that data © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 42 Object-Oriented Programming (2 of 3) An object combines data and operations on the data into a single
  • 23. unit A programming language that implements OOD is called an object-oriented programming (OOP) language To design and use objects, you must learn how to: Represent data in computer memory Manipulate data Implement operations © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 43 Object-Oriented Programming (3 of 3) To create operations: Write algorithms and implement them in a programming language Use functions to implement algorithms Learn how to combine data and operations on the data into a single unit called a class C++ was designed to implement OOD OOD is used with structured design © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#›
  • 24. 44 ANSI/ISO Standard C++ C++ evolved from C C++ designed by Bjarne Stroustrup at Bell Laboratories in early 1980s Many different C++ compilers were available C++ programs were not always portable from one compiler to another In mid-1998, ANSI/ISO C++ language standards were approved Second standard, called C++11, was approved in 2011 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 45 Quick Review (1 of 3) A computer is an electronic device that can perform arithmetic and logical operations A computer system has hardware and software components The central processing unit (CPU) is the brain Primary storage (MM) is volatile; secondary storage (e.g., disk) is permanent The operating system monitors overall activity of the computer and provides services There are various kinds of languages © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 25. classroom use. ‹#› 46 Quick Review (2 of 3) Compiler: translates high-level language into machine code Algorithm: Step-by-step problem-solving process Arrives at a solution in a finite amount of time Problem-solving process Analyze the problem and design an algorithm Implement the algorithm in code Maintain the program © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 47 Quick Review (3 of 3) Structured design Problem is divided into smaller subproblems Each subproblem is solved Combine solutions to all subproblems Object-oriented design (OOD) program: a collection of interacting objects Object: data and operations on those data © 2018 Cengage Learning. All Rights Reserved. May not be
  • 26. copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. ‹#› 48 9781337117562_ppt_ch02.pptx Chapter 2 Basic Elements of C++ © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom C++ Programming: Program Design Including Data Structures, Eighth Edition ‹#› Objectives (1 of 3) In this chapter, you will: Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers Explore simple data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions Become familiar with the string data type Learn what an assignment statement is and what it does
  • 27. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 2 ‹#› 2 Objectives (2 of 3) Learn about variable declaration Discover how to input data into memory using input statements Become familiar with the use of increment and decrement operators Examine ways to output results using output statements Learn how to use preprocessor directives and why they are necessary © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 3 ‹#› Objectives (3 of 3) Learn how to debug syntax errors Explore how to properly structure a program, including using comments to document a program Become familiar with compound statements
  • 28. Learn how to write a C++ program © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 4 ‹#› Introduction Computer program A sequence of statements whose objective is to accomplish a task Programming The process of planning and creating a program Real-world analogy: a recipe for cooking © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 5 ‹#› 5 A Quick Look at a C++ Program (1 of 5) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 29. classroom 6 ‹#› 6 A Quick Look at a C++ Program (2 of 5) Sample Run: © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 7 ‹#› 7 A Quick Look at a C++ Program (3 of 5) FIGURE 2-1 Various parts of a C++ program © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 8 ‹#›
  • 30. 8 A Quick Look at a C++ Program (4 of 5) FIGURE 2-1 Various parts of a C++ program (cont’d.) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 9 ‹#› 9 A Quick Look at a C++ Program (5 of 5) Variable: a memory location whose contents can be changed FIGURE 2-3 Memory allocation FIGURE 2-4 Memory spaces after the statement length = 6.0; executes © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 10 ‹#› 10
  • 31. The Basics of a C++ Program Subprogram (or function): collection of statements When executed, accomplishes something May be predefined or standard Syntax rules: rules that specify which statements (instructions) are legal or valid Semantic rules: determine the meaning of the instructions Programming language: a set of rules, symbols, and special words © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 11 ‹#› 11 Comments Comments are for the reader, not the compiler Two types Single line: begins with // //*************************************************** *********** // Given the length and width of a rectangle, this C++ program // computes and outputs the perimeter and area of the rectangle. //*************************************************** *********** Multiple line: enclosed between /* and */ /* You can include comments that can occupy several lines.
  • 32. */ © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 12 ‹#› 12 Special Symbols A token is the smallest individual unit of a program written in any language C++ tokens include special symbols, word symbols, and identifiers Special symbols in C++ include: +-*/ .;?, <=!===>= © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 13 ‹#› 13 Reserved Words (Keywords) Reserved word symbols (or keywords):
  • 33. Cannot be redefined within a program Cannot be used for anything other than their intended use Examples include: int float double char const void return © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 14 ‹#› 14 Identifiers (1 of 2) An identifier is the name of something that appears in a program Consists 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 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 34. classroom 15 ‹#› 15 Identifiers (2 of 2) Legal identifiers in C++ first conversion payRate TABLE 2-1 Examples of Illegal IdentifiersIllegal IdentifierReasonA Correct Identifieremployee SalaryThere can be no space between employee and Salary.employeeSalaryHello!The exclamation mark cannot be used in an identifier.Helloone+twoThe symbol + cannot be used in an identifier.onePlusTwo2ndAn identifier cannot begin with a digit.second © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 16 ‹#› 16 Whitespaces Every C++ program contains whitespaces Include blanks, tabs, and newline characters Whitespaces separate special symbols, reserved words, and
  • 35. identifiers Proper utilization of whitespaces is important Can be used to make the program more readable © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 17 ‹#› 17 Data Types A data type is set of values together with a set of allowed operations C++ data types fall into three categories: Simple data type Structured data type Pointers © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 18 ‹#› 18 Simple Data Types (1 of 2) Three categories of simple data
  • 36. Integral: integers (numbers without a decimal) Can be further categorized: char, short, int, long, bool, unsigned char, unsigned short, unsigned int, unsigned long Floating-point: decimal numbers Enumeration: a user-defined data type © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 19 ‹#› 19 Simple Data Types (2 of 2) Different compilers may allow different ranges of values TABLE 2-2 Values and Memory Allocation for Simple Data TypesData TypeValuesStorage (in bytes)int–147483648 (= –231 ) to 2147483647 (= 231 – 1)4booltrue and false1char–128 (= – 27 ) to 127 (= 27 – 1)1long long–9223372036854775808 (–263 ) to 9223372036854775807(263 – 1)64 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 20 ‹#›
  • 37. 20 int Data Type Examples -6728 0 78 +763 Positive integers do not require a + sign A comma cannot be used within an integer Commas are only used for separating items in a list © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 21 ‹#› 21 bool Data Type bool type Two values: true and false Purpose: to manipulate logical (Boolean) expressions true and false Logical values bool, true, and false Reserved words © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 38. classroom 22 ‹#› 22 char Data Type (1 of 2) Data type char is the smallest integral data type It is used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character Written ' ', with a space left between the single quotes © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 23 ‹#› 23 char Data Type (2 of 2) Different character data sets exist ASCII: American Standard Code for Information Interchange Each of 128 values in ASCII code set represents a different character Characters have a predefined ordering based on the ASCII numeric value Collating sequence: ordering of characters based on the
  • 39. character set code © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 24 ‹#› 24 Floating-Point Data Types (1 of 3) C++ uses scientific notation to represent real numbers (floating- point notation) TABLE 2-3 Examples of Decimal Numbers in Scientific and C11 Floating-Point NotationsDecimal NumberScientific NotationC++ Floating-Point Notation75.9247.5924 * 1017.592400E10.181.8 * 10-11.800000E-10.00004534.53 * 10- 54.530000E-5–1.482-1.482 * 100-1.482000E07800.07.8 * 1037.800000E3 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 25 ‹#› 25 Floating-Point Data Types (2 of 3) float: represents any real number
  • 40. Range: -3.4 * 1038 to 3.4 * 1038 (four bytes) double: represents any real number Range: –1.7 * 10308 to 1.7 * 10308 (eight bytes) Minimum and maximum values of data types are system dependent © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 26 ‹#› 26 Floating-Point Data Types (3 of 3) Maximum number of significant digits (decimal places) for float values: 6 or 7 Maximum number of significant digits for double: 15 Precision: maximum number of significant digits float values are called single precision double values are called double precision © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 27 ‹#› 27
  • 41. Data Types, Variables, and Assignment Statements To declare a variable, must specify its data type Syntax rule to declare a variable is: dataType identifier; Examples include: int counter; double interestRate; char grade; Assignment statement has the form: variable = expression Example: interestRate = 0.05; © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 28 ‹#› 28 Arithmetic Operators, Operator Precedence, and Expressions (1 of 2) C++ arithmetic operators include: + addition - subtraction (or negation) * multiplication / division % mod (modulus or remainder) +, -, *, and / can be used with integral and floating-point data types Modulus (%) can only be used with integral data types © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product
  • 42. or service or otherwise on a password-protected website for classroom 29 ‹#› 29 Arithmetic Operators, Operator Precedence, and Expressions (2 of 2) When you use / with integral data types, the integral result is truncated (no rounding) Arithmetic expressions contain values and arithmetic operators Operands are the numbers appearing in the expressions Operators can be unary (one operand) or binary (two operands) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 30 ‹#› 30 Order of Precedence All operations inside () are evaluated first *, /, and % are at the same level of precedence and are evaluated next + and - have the same level of precedence and are evaluated last When operators are on the same level Operations are performed from left to right (associativity) 3 * 7 - 6 + 2 * 5 / 4 + 6 means
  • 43. (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 31 ‹#› 31 Expressions Integral expression: all operands are integers Yields an integral result Example: 2 + 3 * 5 Floating-point (decimal) expression: all operands are floating- point Yields a floating-point result Example: 12.8 * 17.5 - 34.50 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 32 ‹#› 32 Mixed Expressions (1 of 2) Mixed expression Has operands of different data types
  • 44. Contains integers and floating-point Examples of mixed expressions 2 + 3.5 6 / 4 + 3.9 5.4 * 2 – 13.6 + 18 / 2 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 33 ‹#› 33 Mixed Expressions (2 of 2) Evaluation rules If operator has same types of operands The operator is evaluated according to the type of the operands If operator has both types of operands Integer is changed to floating-point Operator is evaluated Result is floating-point Entire expression is evaluated according to precedence rules © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 34 ‹#›
  • 45. 34 Type Conversion (Casting) (1 of 2) Implicit type coercion: when the value of one type is automatically changed to another type Cast operator (also called type conversion or type casting): provides explicit type conversion static_cast<dataTypeName>(expression) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 35 ‹#› 35 Type Conversion (Casting) (2 of 2) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 36 ‹#› 36
  • 46. string Type Data type string is a programmer-defined type supplied in ANSI/ISO Standard C++ library A string is a sequence of zero or more characters enclosed in double quotation marks A null (or empty) string is a string with no characters Each character has a relative position in the string Position of first character is 0 The length of a string is the number of characters in it Example: length of "William Jacob" is 13 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 37 ‹#› 37 Variables, Assignment Statements, and Input Statements Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: Instruct the computer to allocate memory Include statements in the program to put data into the allocated memory © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 38
  • 47. ‹#› 38 Allocating Memory with Constants and Variables (1 of2) Named constant: memory location whose content cannot change during execution Syntax to declare a named constant In C++, const is a reserved word © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 39 ‹#› 39 Allocating Memory with Constants and Variables (2 of 2) Variable: memory location whose content may change during execution Syntax to declare one or multiple variables © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 48. classroom 40 ‹#› 40 Putting Data into Variables Ways to place data into a variable Use C++’s assignment statement Use input (read) statements © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 41 ‹#› 41 Assignment Statement (1 of 4) The assignment statement takes the form: Expression is evaluated and its value is assigned to the variable on the left side A variable is said to be initialized the first time a value is placed into it In C++, = is called the assignment operator © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product
  • 49. or service or otherwise on a password-protected website for classroom 42 ‹#› 42 Assignment Statement (2 of 4) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 43 ‹#› 43 Assignment Statement (3 of 4) Example 2-14 illustrates a walk-through (tracing values through a sequence) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 44 ‹#›
  • 50. 44 Assignment Statement (4 of 4) Given int variables x, y, and z. How is this legal C++ statement evaluated? x = y = z The assignment operator is evaluated from right to left The associativity of the assignment operator is from right to left © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 45 ‹#› 45 Saving and Using the Value of an Expression Declare a variable of the appropriate data type Assign the value of the expression to the variable that was declared Use the assignment statement Wherever the value of the expression is needed, use the variable holding the value © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 46
  • 51. ‹#› 46 Declaring and Initializing Variables Not all types of variables are initialized automatically 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 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 47 ‹#› 47 Input (Read) Statement (1 of 3) cin is used with >> to gather one or more inputs This is called an input (read) statement The stream extraction operator is >> For example, if miles is a double variable: cin >> miles; Causes the computer to get a value of type double and places it in the variable miles
  • 52. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 48 ‹#› 48 Input (Read) Statement (2 of 3) Using more than one variable in cin allows more than one value to be read at a time Example: if feet and inches are variables of type int, this statement: cin >> feet >> inches; Inputs two integers from the keyboard Places them in variables feet and inches respectively © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 49 ‹#› 49 Input (Read) Statement (3 of 3) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for
  • 53. use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 50 ‹#› 50 Increment and Decrement Operators Increment operator (++): increase variable by 1 Pre-increment: ++variable Post-increment: variable++ Decrement operator: (--) decrease variable by 1 Pre-decrement: --variable Post-decrement: variable-- What is the difference between the following? x = 5; y = ++x; x = 5; y = x++; © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 51 ‹#› 51 Output (1 of 4)
  • 54. The syntax of cout and << is: Called an output statement The stream insertion operator is << Expression evaluated and its value is printed at the current cursor position on the screen © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 52 ‹#› 52 Output (2 of 4) A manipulator is used to format the output Example: endl causes the insertion point to move to beginning of next line © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 53 ‹#› 53
  • 55. Output (3 of 4) The new line character (new line escape sequence) is 'n' May appear anywhere in the string Examples cout << "Hello there."; cout << "My name is James."; Output: Hello there.My name is James. cout << "Hello there.n"; cout << "My name is James."; Output : Hello there. My name is James. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 54 ‹#› 54 Output (4 of 4) TABLE 2-4 Commonly Used Escape SequencesEscape SequenceDescriptionnNewlineCursor moves to the beginning of the next linetTabCursor moves to the next tab stopbBackspaceCursor moves one space to the leftrReturnCursor moves to the beginning of the current line (not the next line)BackslashBackslash is printed'Single quotationSingle quotation mark is printed"Double quotationDouble quotation mark is printed © 2018 Cengage Learning. All Rights Reserved. May not be
  • 56. copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 55 ‹#› 55 Preprocessor Directives (1 of 2) C++ has a small number of operations Many functions and symbols needed to run a C++ program are provided as collection of libraries Every library has a name and is referred to by a header file Preprocessor directives are processed by the preprocessor program All preprocessor commands begin with # No semicolon is placed at the end of these commands © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 56 ‹#› 56 Preprocessor Directives (2 of 2) Syntax to include a header file
  • 57. For example: #include <iostream> Causes the preprocessor to include the header file iostream in the program Preprocessor commands are processed before the program goes through the compiler © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 57 ‹#› 57 namespace and Using cin and cout in a Program cin and cout are declared in the header file iostream, but within std namespace To use cin and cout in a program, use the following two statements: #include <iostream> using namespace std; © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 58 ‹#›
  • 58. 58 Using the string Data Type in a Program To use the string type, you need to access its definition from the header file string Include the following preprocessor directive: #include <string> © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 59 ‹#› 59 Creating a C++ Program (1 of 3) A C++ program is a collection of functions, one of which is the function main The syntax of the function main used in this book has this form: © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 60
  • 59. ‹#› 60 Creating a C++ Program (2 of 3) Source code is comprised of preprocessor directives and program statements The source code file (source file) contains the source code The compiler generates the object code (file extension .obj) Executable code (file extension .exe) results when object code is linked with the system resources The first line of the function main is called the heading of the function: int main() © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 61 ‹#› 61 Creating a C++ Program (3 of 3) The statements enclosed between the curly braces ({ and }) form the body of the function A C++ program contains two types of statements:
  • 60. Declaration statements declare things, such as variables Executable statements perform calculations, manipulate data, create output, accept input, etc. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 62 ‹#› 62 Debugging: Understanding and Fixing Syntax Errors (1 of 2) Sample program with line numbers added on the left © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 63 ‹#› 63 Debugging: Understanding and Fixing Syntax Errors (2 of 2) Compile the program Compiler will identify the syntax errors The line numbers where the errors occur are specified: ExampleCh2_Syntax_Errors.cpp c:examplech2_syntax_errors.cpp(9): error C2146: syntax error:
  • 61. missing ';' before identifier 'num' c:examplech2_syntax_errors.cpp(11): error C2065: 'tempNum': undeclared identifier © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 64 ‹#› 64 Program Style and Form: Syntax Syntax rules indicate what is legal and what is not legal Errors in syntax are found in compilation int x;//Line 1 int y//Line 2 double z;//Line 3 y = w + x;//Line 4 Compilation errors would occur at: Line 2 (missing semicolon) Line 4 (identifier w used but not declared) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 65 ‹#›
  • 62. 65 Use of Blanks In C++, you use one or more blanks to separate numbers when data is input Blanks are also used to separate reserved words and identifiers from each other and from other symbols Blanks must never appear within a reserved word or identifier © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 66 ‹#› 66 Use of Semicolons, Brackets, and Commas All C++ statements end with a semicolon Also called a statement terminator { and } are not C++ statements Can be regarded as delimiters Commas separate items in a list Declaring more than one variable following a data type © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 67 ‹#›
  • 63. 67 Semantics Semantics: set of rules that gives meaning to a language Possible to remove all syntax errors in a program and still not have it run Even if it runs, it may still not do what you meant it to do Example: 2 + 3 * 5 and (2 + 3) * 5 Both are syntactically correct expressions but have different meanings © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 68 ‹#› 68 Naming Identifiers Identifiers can be self-documenting CENTIMETERS_PER_INCH Avoid run-together words annualsale Solution
  • 64. s may include: Capitalizing the beginning of each new word: annualSale Inserting an underscore just before a new word: annual_sale © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 69 ‹#› 69 Prompt Lines Prompt lines: executable statements that inform the user what to do cout << "Please enter a number between 1 and 10 and " << "press the return key" << endl; cin >> num; Always include prompt lines when input is needed from users © 2018 Cengage Learning. All Rights Reserved. May not be
  • 65. copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 70 ‹#› 70 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 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 71
  • 66. ‹#› 71 Form and Style Consider two ways of declaring variables: Method 1 int feet, inches; double x, y; Method 2 int feet,inches; double x,y; Both are correct; however, the second is harder to read © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 72 ‹#› 72
  • 67. More on Assignment Statements Two forms of assignment Simple and compound Compound operators provide more concise notation Compound operators: +=, -=, *=, /=, %= Simple assignment statement example x = x * y; Compound assignment statement example x *= y; © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 73 ‹#› 73 Quick Review (1 of 3) A C++ program is a collection of functions, one of which is always called main Identifiers consist of letters, digits, and underscores, and begin
  • 68. with a letter or an underscore The arithmetic operators in C++ are addition (+), subtraction (- ), multiplication (*), division (/), and modulus (%) Arithmetic expressions are evaluated using the precedence associativity rules © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 74 ‹#› 74 Quick Review (2 of 3) All operands in an integral expression are integers All operands in a floating-point expression are decimal numbers A mixed expression contains both integers and decimal numbers Use the cast operator to explicitly convert values from one data type to another A named constant is initialized when declared All variables must be declared before used
  • 69. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 75 ‹#› 75 Quick Review (3 of 3) Use cin and the stream extraction operator >> to input from the standard input device Use cout and the stream insertion operator << to output to the standard output device Preprocessor commands are processed before the program goes through the compiler A file containing a C++ program usually ends with the extension .cpp © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 70. classroom 76 ‹#› 76 9781337117562_ppt_ch03.pptx Chapter 3 Input/Output C++ Programming: Program Design Including Data Structures, Eighth Edition ‹#› 1 Objectives (1 of 2) In this chapter, you will:
  • 71. Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined functions in a program Explore how to use the input stream functions get, ignore, putback, and peek © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 2 ‹#› 2 Objectives (2 of 2) Become familiar with input failure Learn how to write data to the standard output device Discover how to use manipulators in a program to format output Learn how to perform input and output operations with the string data type Learn how to debug logic errors Become familiar with file input and output
  • 72. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 3 ‹#› 3 I/O Streams and Standard I/O Devices (1 of 3) I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters from the source to the destination Input stream: sequence of characters from an input device to the computer Output stream: sequence of characters from the computer to an output device © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for
  • 73. use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 4 ‹#› 4 I/O Streams and Standard I/O Devices (2 of 3) Use iostream header file to receive data from keyboard and send output to the screen Contains definitions of two data types: istream: input stream ostream: output stream Has two variables: cin: stands for common input cout: stands for common output © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 5
  • 74. ‹#› 5 I/O Streams and Standard I/O Devices (3 of 3) Variable declaration is similar to: istream cin; ostream cout; To use cin and cout, the preprocessor directive#include <iostream> must be used Input stream variables: type istream Output stream variables: type ostream © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 6 ‹#› 6
  • 75. cin and the Extraction Operator >> (1 of 7) The syntax of an input statement using cin and the extraction operator >> is The extraction operator >> is binary Left-side operand is an input stream variable Example: cin Right-side operand is a variable © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 7 ‹#› 7 cin and the Extraction Operator >> (2 of 7) No difference between a single cin with multiple variables and multiple cin statements with one variable in each statement
  • 76. cin >> payRate >> hoursWorked; cin >> payRate; cin >> hoursWorked; When scanning, >> skips all whitespace Blanks and certain nonprintable characters >> distinguishes between character 2 and number 2 by the right- side operand of >> If type char or int (or double), the 2 is treated as a character or as a number 2, respectively © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 8 ‹#› 8 cin and the Extraction Operator >> (3 of 7) TABLE 3-1 Valid Input for a Variable of the Simple Data TypeData Type of aValid Input for acharOne printable character
  • 77. except the blank.intAn integer, possibly preceded by a + or - sign.doubleA decimal number, possibly preceded by a + or - sign. If the actual data input is an integer, the input is converted to a decimal number with the zero decimal part. Entering a char value into an int or double variable causes serious errors, called input failure © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 9 ‹#› 9 cin and the Extraction Operator >> (4 of 7) When reading data into a char variable >> skips leading whitespace, finds and stores only the next character Reading stops after a single character To read data into an int or double variable >> skips leading whitespace, reads + or - sign (if any), reads the
  • 78. digits (including decimal for floating-point variables) Reading stops on whitespace or a non-digit character © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 10 ‹#› 10 cin and the Extraction Operator >> (5 of 7) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 11 ‹#›
  • 79. 11 cin and the Extraction Operator >> (6 of 7) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 12 ‹#› 12 cin and the Extraction Operator >> (7 of 7) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 13
  • 80. ‹#› 13 Using Predefined Functions in a Program (1 of 3) A function (subprogram) is a set of instructions When activated, it accomplishes a task main executes when a program is run Other functions execute only when called C++ includes a wealth of functions Predefined functions are organized as a collection of libraries called header files © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 14 ‹#› 14
  • 81. Using Predefined Functions in a Program (2 of 3) Header file may contain several functions To use a predefined function, you need the name of the appropriate header file You also need to know: Function name Number of parameters required Type of each parameter What the function is going to do © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 15 ‹#› 15 Using Predefined Functions in a Program (3 of 3) To use pow (power), include cmath
  • 82. Two numeric parameters Syntax: pow(x,y) = xy x and y are the arguments or parameters In pow(2,3), the parameters are 2 and 3 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 16 ‹#› 16 cin and the get Function The get function Inputs next character (including whitespace) Stores in memory location indicated by its argument The syntax of cin and the get function varChar is a char variable It is the argument (or parameter) of the function
  • 83. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 17 ‹#› 17 cin and the ignore Function (1 of 2) ignore function Discards a portion of the input The syntax to use the function ignore is: intExp is an integer expression chExp is a char expression If intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExp © 2018 Cengage Learning. All Rights Reserved. May not be
  • 84. copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 18 ‹#› 18 cin and the ignore Function (2 of 2) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 19 ‹#› 19
  • 85. The putback and peek Functions (1 of 2) putback function Places previous character extracted by the get function from an input stream back to that stream peek function Returns next character from the input stream Does not remove the character from that stream © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 20 ‹#› 20 The putback and peek Functions (2 of 2) Syntax for putback istreamVar: an input stream variable (such as cin) ch is a char variable Syntax for peek
  • 86. istreamVar: an input stream variable (such as cin) ch is a char variable © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 21 ‹#› 21 The Dot Notation between I/O Stream Variables and I/O Functions: A Precaution In the statement cin.get(ch); cin and get are two separate identifiers separated by a dot Called the dot notation, the dot separates the input stream variable name from the member, or function, name
  • 87. In C++, the dot is the member access operator © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 22 ‹#› 22 Input Failure Things can go wrong during execution If input data does not match corresponding variables, the program may run into problems Trying to read a letter into an int or double variable will result in an input failure If an error occurs when reading data Input stream enters the fail state © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 88. classroom 23 ‹#› 23 The clear Function Once in a fail state, all further I/O statements using that stream are ignored The program continues to execute with whatever values are stored in variables This causes incorrect results The clear function restores the input stream to a working state The syntax of the function clear is: © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 24 ‹#›
  • 89. 24 Output and Formatting Output Syntax of cout when used with << expression is evaluated value is printed manipulator is used to format the output Example: endl © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 25 ‹#› 25 setprecision Manipulator
  • 90. Syntax Outputs decimal numbers with up to n decimal places Must include the header file iomanip #include <iomanip> © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 26 ‹#› 26 fixed Manipulator fixed outputs floating-point numbers in a fixed decimal format Example: cout << fixed; Disable by using the stream member function unsetf Example: cout.unsetf(ios::fixed); scientific manipulator outputs floating-point numbers in scientific format
  • 91. © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 27 ‹#› 27 showpoint Manipulator showpoint forces output to show the decimal point and trailing zeros Examples cout << showpoint; cout << fixed << showpoint; © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 28
  • 92. ‹#› 28 C++14 Digit Separator Reading and writing of long numbers can be error prone In C++, commas cannot be used to separate the digits of a number C++14 introduces digit separator ' (single-quote character) Example: 87523872918 can be represented as 87'523'872'918 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 29 ‹#› 29 setw
  • 93. Outputs the value of an expression in a specified number of columns cout << setw(5) << x << endl; If number of columns exceeds the number of columns required by the expression Output of the expression is right-justified Unused columns to the left are filled with spaces Must include the header file iomanip © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 30 ‹#› 30 Additional Output Formatting Tools Additional formatting tools that give you more control over your output: setfill manipulator left and right manipulators
  • 94. unsetf manipulator © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 31 ‹#› 31 setfill Manipulator Output stream variables can use setfill to fill unused columns with a character Example: cout << setfill('#'); © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product
  • 95. or service or otherwise on a password-protected website for classroom 32 ‹#› 32 left and right Manipulators left manipulator left-justifies the output Disable left by using unsetf right manipulator right-justifies the output © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 33 ‹#›
  • 96. 33 Types of Manipulators Two types of manipulators Those with parameters Those without parameters Parameterized stream manipulators require the iomanip header setprecision, setw, and setfill Manipulators without parameters require the iostream header endl, fixed, scientific, showpoint, and left © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 34 ‹#› 34 Input/Output and the string Type An input stream variable (such as cin) and >> operator can read
  • 97. a string into a variable of the data type string The extraction operator: Skips any leading whitespace characters Stops reading at a whitespace character The function getline reads until end of the current line © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 35 ‹#› 35 Debugging: Understanding Logic Errors and Debugging with cout statements Syntax errors are reported by the compiler Logic errors are typically not caught by the compiler Spot and correct using cout statements Temporarily insert an output statement Correct the problem
  • 98. Remove output statement © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 36 ‹#› 36 File Input/Output A file is an area in secondary storage to hold info File I/O is a five-step process Include fstream header Declare file stream variables Associate the file stream variables with the input/output sources – referred to as opening the files Use the file stream variables with >>, <<, or other input/output functions Close the files © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for
  • 99. use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 37 ‹#› 37 Quick Review (1 of 3) 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 cin: common input cout: common output To use cin and cout, include iostream header © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 38
  • 100. ‹#› 38 Quick Review (2 of 3) get reads data character-by-character ignore skips data in a line putback puts last character retrieved by get back to the input stream 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 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 39 ‹#› 39
  • 101. Quick Review (3 of 3) The manipulators setprecision, fixed, showpoint, setw, setfill, left, and right can be used for formatting output Include iomanip for the manipulators setprecision, setw, and setfill Header fstream contains the definitions of ifstream and ofstream © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom 40 ‹#› 40 9781337117562_ppt_ch04.pptx Chapter 4 Control Structures I (Selection)
  • 102. C++ Programming: Program Design Including Data Structures, Eighth Edition ‹#› 1 Objectives (1 of 2) In this chapter, you will: Learn about control structures Examine relational operators Discover how to use the selection control structures if, if…else Examine int and bool data types and logical (Boolean) expressions Examine logical operators Explore how to form and evaluate logical (Boolean) expressions © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#›
  • 103. 2 Objectives (2 of 2) Learn how relational operators work with the string type Become aware of short-circuit evaluation Learn how the conditional operator, ?:, works Learn how to use pseudocode to develop, test, and debug a program Discover how to use a switch statement in a program Learn how to avoid bugs by avoiding partially understood concepts Learn how to use the assert function to terminate a program © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 3
  • 104. Control Structures (1 of 2) A computer can proceed: In sequence Selectively (branch): making a choice Repetitively: looping By calling a function The two most common control structures are: Selection Repetition © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 4 Control Structures (2 of 2) FIGURE 4-1 Flow of execution © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for
  • 105. use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 5 Selection: if and if...else An expression that evaluates to true or false is called a logical expression “8 is greater than 3” is true © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 6 Relational Operators
  • 106. TABLE 4-1 Relational Operators in C++OperatorDescription==equal to!=not equal to<less than<=less than or equal to>greater than>=greater than or equal to Each relational operator is a binary operator (requires two operands) Expressions using these operators always evaluate to true or false © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› Relational Operators and Simple Data Types You can use the relational operators with all three simple data types © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom
  • 107. ‹#› 8 Comparing Characters In an expression of char values using relational operators: The result depends on the machine’s collating sequence ASCII character set Logical (Boolean) expressions: Include expressions such as 4 < 6 and 'R' > 'T’ Return an integer value of 1 if the logical expression evaluates to true Return an integer value of 0 otherwise © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 9
  • 108. One-Way Selection (1 of 2) One-way selection syntax The statement is: Executed if the value of the expression is true Bypassed if the value is false; program goes to the next statement The expression is also called a decision maker The statement following the expression is also called the action statement © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 10 One-Way Selection (2 of 2)
  • 109. FIGURE 4-2 One-way selection © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 11 Two-Way Selection (1 of 2) Two-way selection syntax If expression is true, statement1 is executed; otherwise, statement2 is executed statement1 and statement2 are any C++ statements © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom
  • 110. ‹#› 12 Two-Way Selection (2 of 2) FIGURE 4-3 Two-way selection © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 13 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 Logical expression value was stored in a variable of the data type int
  • 111. You can use the int data type to manipulate logical (Boolean) expressions © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 14 bool Data Type and Logical (Boolean) Expressions The data type bool has logical (Boolean) values true and false bool, true, and false are reserved words The identifier true has the value 1 The identifier false has the value 0 © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
  • 112. classroom ‹#› 15 Logical (Boolean) Operators and Logical Expressions (1 of 5) Logical (Boolean) operators enable you to combine logical expressions TABLE 4-2 Logical (Boolean) Operators in C++OperatorDescription!not&&and||or © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 16 Logical (Boolean) Operators and Logical Expressions (2 of 5) TABLE 4-3 The ! (Not) OperatorExpression!(Expression)true
  • 113. (nonzero)false (0)false (0)true (1) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 17 Logical (Boolean) Operators and Logical Expressions (3 of 5) TABLE 4-4 The && (And) OperatorExpression1Expression2Expression1 && Expression2true (nonzero)true (nonzero)true (1)true (nonzero)false (0)false (0)false (0)true (nonzero)false (0)false (0)false (0)false (0) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom
  • 114. ‹#› 18 Logical (Boolean) Operators and Logical Expressions (4 of 5) TABLE 4-5 The || (Or) OperatorExpression1Expression2Expression1 || Expression2true (nonzero)true (nonzero)true (1)true (nonzero)false (0)true (1)false (0)true (nonzero)true (1)false (0)false (0)false (0) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 19 Logical (Boolean) Operators and Logical Expressions (5 of 5) © 2018 Cengage Learning. All Rights Reserved. May not be
  • 115. copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› Order of Precedence (1 of 5) Relational and logical operators are evaluated from left to right The associativity is left to right Parentheses can override precedence © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 21 Order of Precedence (2 of 5) TABLE 4-6 Precedence of OperatorsOperatorsPrecedence!, +, - (unary operators)first*, /, %second+, -third<, <=, >=,
  • 116. >fourth==, !=fifth&&sixth||seventh= (assignment operator)last © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 22 Order of Precedence (3 of 5) © 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom ‹#› 23