computer programme
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
| Unit | Symbol | Bits/Bytes |
| Byte | 8 bits | |
| Kilobyte | KB | 210 bytes = 1024 bytes |
| Megabyte | MB | 1024 KB = 210 KB = 220 bytes = 1,048,576 bytes |
| Gigabyte | GB | 1024MB = 210 MB = 230 bytes = 1,073,741,824 bytes |
| Terabyte | TB | 1024 GB = 210 GB = 240 bytes = 1,099,511,627,776 bytes |
| Petabyte | PB | 1024 TB = 210 TB = 250 bytes = 1,125,899,906,842,624 bytes |
| Exabyte | EB | 1024 PB = 210 PB = 260 bytes = 1,152,921,504,606,846,976 bytes |
| Zettabyte | ZB | 1024 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 Identifiers
| Illegal Identifier | Reason | A Correct Identifier |
| employee Salary | There can be no space between employee and Salary. | employeeSalary |
| Hello! | The exclamation mark cannot be used in an identifier. | Hello |
| one+two | The symbol + cannot be used in an identifier. | onePlusTwo |
| 2nd | An 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 Types
| Data Type | Values | Storage (in bytes) |
| int | –147483648 (= –231 ) to 2147483647 (= 231 – 1) | 4 |
| bool | true and false | 1 |
| char | –128 (= –27 ) to 127 (= 27 – 1) | 1 |
| long 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 Notations
| Decimal Number | Scientific Notation | C++ Floating-Point Notation |
| 75.924 | 7.5924 * 101 | 7.592400E1 |
| 0.18 | 1.8 * 10-1 | 1.800000E-1 |
| 0.0000453 | 4.53 * 10-5 | 4.530000E-5 |
| –1.482 | -1.482 * 100 | -1.482000E0 |
| 7800.0 | 7.8 * 103 | 7.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 Sequences
| Escape Sequence | Description | |
| \n | Newline | Cursor moves to the beginning of the next line |
| \t | Tab | Cursor moves to the next tab stop |
| \b | Backspace | Cursor moves one space to the left |
| \r | Return | Cursor moves to the beginning of the current line (not the next line) |
| \\ | Backslash | Backslash is printed |
| \' | Single quotation | Single quotation mark is printed |
| \" | Double quotation | Double 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
Solutions 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 Type
| Data Type of a | Valid Input for a |
| char | One printable character except the blank. |
| int | An integer, possibly preceded by a + or - sign. |
| double | A 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++
| Operator | Description |
| == | 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++
| Operator | Description |
| ! | 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) Operator
| Expression | !(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) Operator
| Expression1 | Expression2 | Expression1 && Expression2 |
| true (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) Operator
| Expression1 | Expression2 | Expression1 || Expression2 |
| true (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 Operators
| Operators | Precedence |
| !, +, - (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
Order of Precedence (4 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
‹#›
24
Order of Precedence (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
‹#›
25
Relational Operators and the string Type (1 of 5)
Relational operators can be applied to variables of type string
Strings are compared character by character, starting with the first character
Comparison continues until either a mismatch is found or all characters are found equal
If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string
The shorter string is less than the larger string
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, 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
Relational Operators and the string Type (2 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