際際滷

際際滷Share a Scribd company logo
Chapter 2
Introduction to C++
Starting Out with C++ Early Objects
Seventh Edition
by Tony Gaddis, Judy Walters,
and Godfrey Muganda
2-1
2.1 Parts of a C++ Program
// sample C++ program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, there!";
return 0;
}
2-2
comment
preprocessor directive
which namespace to use
beginning of function named main
beginning of block for main
output statement
send 0 back to operating system
end of block for main
Special Characters (pg. 30)
2-3
Character Name Description
// Double Slash Begins a comment
# Pound Sign Begins preprocessor directive
< > Open, Close Brackets Encloses filename used in
#include directive
( ) Open, Close Parentheses Used with function & other
times
{ } Open, Close Braces Encloses a group of statements
" " Open, Close Quote Marks Encloses string of characters
; Semicolon Ends a programming statement
Important Details
 C++ is case-sensitive. Uppercase &
lowercase characters are different
characters. Main is not the same as
main.
 Every { must have a corresponding },
and vice-versa.
Watch for the NOTE and WARNING boxes n
your text. They provide good information! 2-4
2.2 The cout Object
 Displays information on computer screen
 Equivalent to print to screen
 Use << to send information to cout
cout << "Hello, there!";
 Can use << to send multiple items to cout
cout << "Hello, " << "there!";
Or equivalently
cout << "Hello, ";
cout << "there!"; 2-5
cout
 << stream insertion operator
 Must be between each different element
cout << Total is  << Tot;
Total is 49
2-6
Starting a New Line
 To get multiple lines of output on screen
- Use endl
cout << "Hello, there!" << endl;
- Use n in an output string
cout << "Hello, there!n";
2-7
New lines of output
endl  a command
 Causes a new line of output
 Dumps the output buffer to output file
n  a special character
 Causes a new line of output only
 MUST be inside quotes
 Side-effect: when used with file output,
some output may not get printed
Test question
2-8
Common Escape Sequences (p.35)
~~ MUST be contained in quotes
~~ Considered a single character
n Newline
t Tab
a Alarm
b Backspace
r Return (same line)
 Prints 1 
 Prints single quote
 Prints double quote 2-9
Examples
cout << Hellon Mary;
Hello
Mary
Note: the single space in front of Mary
2-10
2.3 The #include Directive
 Inserts the contents of another file into the
program
 Is a preprocessor directive
 Not part of the C++ language
 Not seen by compiler
 Example:
#include <iostream>
There will be several different files that we will include
for different purposes. 2-11
No
semicolon;
goes here
2.4 Standard & Pre-standard C++
Older-style C++ programs
 Use .h at end of header files
#include <iostream.h>
 Do not use using namespace convention
 May not compile with a standard C++ compiler
We WILL NOT use the .h format.
2-12
2.5 Variables, Constants, & the
Assignment Statement
 Variable
 Has a name (identifier) & a type of data it can hold
char letter;
 Is used to reference a location in memory where a
value can be stored
 Must be defined before it can be used
 The value that is stored can be changed,
i.e., it can vary
 When use name in program, referring to data stored
in the corresponding memory location.
2-13
variable
name
data type
Variables
 Represents a location in memory
 Stores/Holds on data value
 If a new value is stored in the variable, it
replaces previous value
 The previous value is overwritten and can no
longer be retrieved
int age;
age = 17; // age is 17
cout << age; // Displays 17
age = 18; // Now age is 18
cout << age; // Displays 18 2-14
Assignment Statement
 Uses the = operator (is assigned)
 Has single variable on left side and a
value or expression on right side
 Copies the value on right into the
variable on left, i.e. its memory location
item = 12;
total = 15 + 2;
tax = Bal * 0.0825; 2-15
Constant
 Data item whose value does not change
during program execution  NEVER
 Is also called a literal
'A' // character constant
"Hello" // string literal
12 // integer constant
3.14 // floating-point constant
Often a test question
2-16
2.6 Identifiers
 Programmer-chosen names to represent parts of
program, such as variables & constants
 Any length, but you must type it repeatedly
 Name indicates use of the identifier
 Cannot use C++ key words as identifiers
 See Table 2.4  pg. 41
 Legal form (this is a question on test 1)
 Must begin with alphabetic character or _
 followed by alphabetic, numeric, or _ . Alpha may be
upper- or lowercase
2-17
Valid and Invalid
Identifiers
2-18
IDENTIFIER VALID? REASON IF INVALID
totalSales Yes
total_Sales Yes
total.Sales No Cannot contain period
4thQtrSales No Cannot begin with digit
totalSale$ No Cannot contain $
2.7 Integer Data Types
 Designed to hold whole numbers
 Can be signed or unsigned
12 -6 +3
 Available in different sizes (i.e., number of
bytes): short, int, and long
 size of short  size of int  size of long
Table 2-6  pg. 44
2-19
Defining Variables
 Variables of the same type can be defined
- In separate statements
int length;
int width;
- In the same statement
int length, width;
 Variables of different types must be defined
in separate statements
int length;
short width;
2-20
2.8 The char Data Type
 Used to hold single characters
 Or very small integer values: 0 to 15 *but dont*
 (Usually) Occupies 1 byte of memory
 A numeric code representing the character
is stored in memory
2-21
SOURCE CODE MEMORY
char letter = c'; letter
0110 0011
String Constant
 Can be stored a series of characters in
consecutive memory locations
"Hello"
 Stored with null terminator, 0, at end
 Is comprised of characters between
the " "
2-22
H e l l o 0
A character or a string constant?
 A character constant is a single character,
enclosed in single quotes:
'C'
 A string constant is a sequence of
characters enclosed in double quotes:
"Hello, there!"
 A single character in double quotes is a
string constant, not a character constant:
"C"
2-23
2.9 The C++ string Class
 Must #include <string> to create & use
string objects
 Can define string variables in programs
string name;
 Can assign values to string variables with
assignment operator
name = "George";
 Can display with cout
cout << name;
 Note: # include <string> unnecessary if using
only string literals
cout << George; 2-24
2.10 Floating-Point Data Types
 Hold real numbers
12.45 -3.8
 Stored in form similar to scientific notation
 Numbers are all signed
 Types are
 float - 4 bytes
 double  8 bytes
 long double  8 bytes (usually)
2-25
Floating Point Examples
float Item, Tax;
Item = 5.34;
Tax = Item * 0.0825;
cout << Item <<   << Tax;
----------------------
5.34 0.44055
Note: w/o spaces in quotes
5.340.44055 2-26
Floating-point Constants
 Can be represented in
- Fixed point (decimal) notation:
31.4159 0.0000625
- E-notation: (we wont use but need to recognize)
3.14159E1 6.25e-5
Usually indicate extremely large
or small value
 Are double by default
2-27
Assigning Floating-point
Values to Integer Variables
If floating-point value is assigned to an
integer variable
 The fractional part will be truncated
(i.e., chopped off & discarded)
 The value is NOT rounded
int rainfall = 3.88;
cout << rainfall; // Displays 3
2-28
2.11 The bool Data Type
 Represents values that are true or false
 bool values are stored as short integers
 false is represented by 0, true by 1
bool allDone = true;
bool finished = false;
Note: Any non-zero value is considered
true. 2-29
allDone finished
1 0
2.12 Determining the Size
of a Data Type
The sizeof operator gives size of any data
type or variable
double amount;
cout << "A float is stored in "
<< sizeof(float) << " bytesn";
cout << "Variable amount is stored in "
<< sizeof(amount) << " bytesn";
2-30
2.13 More on Variable
Assignments and Initialization
 Assigning value to a variable
 Assigns a value to a previously created variable
 A single variable name must appear on left side
of the = symbol
int size;
size = 5; // legal
5 = size; // not legal
2-31
Variable Assignment vs.
Initialization
 Initializing a variable
 Gives initial value to variable at time it is
created
 Can initialize some or all variables of
definition
int length = 12;
int width = 7, height = 5, area;
2-32
What if a variable is not initialized??
double amount;
cout << amount;
What happens?? . It depends
*Ignore - continues, repeats message
*Abort  program stops
*Retry  tries again then stops
- get MS send error report?
2-33
2.14 Scope
 The scope of a variable is that part of the
program where the variable may be used
 Scope of variable begins with definition,
continues through the block in which it is
defined
 A variable cannot be used before it is defined
int a;
cin >> a; // legal
cin >> b; // illegal
int b;
 (Test question)
2-34
Scope
To avoid problems
 Define ALL variables & constants at the
beginning of the program!!!
 Later we will discuss other issues
related to scope.
2-35
2.15 Arithmetic Operators
 Used for performing numeric calculations
 C++ has unary, binary, and ternary
operators
 unary (1 operand) -5
 binary (2 operands) 13 - 7
 ternary (3 operands) exp1 ? exp2 : exp3
2-36
Binary Arithmetic
Operators
2-37
SYMBOL OPERATION EXAMPLE ans
+ addition ans = 7 + 3; 10
- subtraction ans = 7 - 3; 4
* multiplication ans = 7 * 3; 21
/ division ans = 7 / 3; 2
% modulus ans = 7 % 3; 1
Order of operation is standard mathematics.
/ Operator
 C++ division operator (/)performs integer
division if both operands are integers
cout << 13 / 5; // displays 2
cout << 2 / 4; // displays 0
 If either operand is floating-point, the result
is floating-point
cout << 13 / 5.0; // displays 2.6
cout << 2.0 / 4; // displays 0.5
2-38
% Operator - Modulus
 Same priority as * and /
 C++ modulus operator (%) computes the
remainder resulting from integer division
cout << 9 % 2; // displays 1
 % requires integers for both operands
cout << 9 % 2.0; // error
2-39
2.16 Comments
 Used to document parts of program
 Written for persons reading source code
of program
 Indicate purpose of program
 Describe use of variables
 Explain complex sections of code
 Ignored by compiler
 REQUIRED for all programs (by RH)
 No absolute rules, but STANDARDS 2-40
Single-Line Comments
 Begin with // through to the end of line
int length = 12; // length in inches
int width = 15; // width in inches
int area; // calculated area
// Calculate rectangle area
area = length * width;
2-41
Multi-Line Comments
 Begin with /* & end with */
 Can span multiple lines
/*----------------------------
Here's a multi-line comment
----------------------------*/
 Can be used as single-line comments
int area; /* Calculated area */
 MUST have both
2-42
Comment Guidelines
 Use your textbook as a GOOD Example
 Always comment with name, project name,
project description at beginning of every
program
 Descriptive comments within body of program
are REQUIRED
 If comment is so generic it could be moved to any
other program then it is not a good comment
 If comment states exactly what the codes says
then it is not a good comment
2-43
Chapter 2 Homework
 Checkpoints
 These are at the end of most sections (e.g. page
31). You should do all of these
 End of Chapter questions 
 Page 70+; All (1  27) 8E
 Quizzes will usually come from checkpoints &
end of chapter questions
2-44

More Related Content

Similar to Chapter 2 Introduction to C++ (20)

Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
Terry Yoast
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
FatimaZafar68
C++ programming
C++ programmingC++ programming
C++ programming
Anshul Mahale
C Intro.ppt
C Intro.pptC Intro.ppt
C Intro.ppt
DaVidSilenceKawlni
C_chap02.ppt Introduction to C Programming Language
C_chap02.ppt Introduction to C Programming LanguageC_chap02.ppt Introduction to C Programming Language
C_chap02.ppt Introduction to C Programming Language
anithasancs
intro to c
intro to cintro to c
intro to c
teach4uin
C Introduction
C IntroductionC Introduction
C Introduction
Sudharsan S
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
ahmed abugharsa
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
Nico Ludwig
Chapter2
Chapter2Chapter2
Chapter2
Anees999
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptxKMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
Unit No 2.pptx Basic s of C Programming
Unit No 2.pptx   Basic s of C ProgrammingUnit No 2.pptx   Basic s of C Programming
Unit No 2.pptx Basic s of C Programming
Vaibhav Parjane
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
Walepak Ubi
Lecture 01 2017
Lecture 01 2017Lecture 01 2017
Lecture 01 2017
Jesmin Akhter
Elementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.pptElementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.ppt
GordanaJovanoska1
Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
Terry Yoast
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
FatimaZafar68
C_chap02.ppt Introduction to C Programming Language
C_chap02.ppt Introduction to C Programming LanguageC_chap02.ppt Introduction to C Programming Language
C_chap02.ppt Introduction to C Programming Language
anithasancs
intro to c
intro to cintro to c
intro to c
teach4uin
C Introduction
C IntroductionC Introduction
C Introduction
Sudharsan S
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
Nico Ludwig
Chapter2
Chapter2Chapter2
Chapter2
Anees999
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptxKMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
Unit No 2.pptx Basic s of C Programming
Unit No 2.pptx   Basic s of C ProgrammingUnit No 2.pptx   Basic s of C Programming
Unit No 2.pptx Basic s of C Programming
Vaibhav Parjane
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
Walepak Ubi
Elementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.pptElementary_Of_C++_Programming_Language.ppt
Elementary_Of_C++_Programming_Language.ppt
GordanaJovanoska1

Recently uploaded (20)

Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlanMaximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
OnePlan Solutions
Managing Changing Data with FME Part 1 - Compare & Detect
Managing Changing Data with FME Part 1 - Compare & DetectManaging Changing Data with FME Part 1 - Compare & Detect
Managing Changing Data with FME Part 1 - Compare & Detect
Safe Software
ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025
umeerbinfaizan
Internet Download Manager Crack Latest version 2025
Internet Download Manager  Crack Latest version 2025Internet Download Manager  Crack Latest version 2025
Internet Download Manager Crack Latest version 2025
mohsinrazakpa26
Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)
blouch36kp
Digital Application Development Services
Digital Application Development ServicesDigital Application Development Services
Digital Application Development Services
daavishenry
Byteexpo Call Center - Presentation.pptx
Byteexpo Call Center - Presentation.pptxByteexpo Call Center - Presentation.pptx
Byteexpo Call Center - Presentation.pptx
hmk11790
Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...
Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...
Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...
KCD Guadalajara
Virtual DJ Pro Crack 2025 Full Version Download [Latest]
Virtual DJ Pro Crack 2025 Full Version Download [Latest]Virtual DJ Pro Crack 2025 Full Version Download [Latest]
Virtual DJ Pro Crack 2025 Full Version Download [Latest]
umeerbinfaizan
Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]
l07307095
mORMot 2 - Pascal Cafe 2025 in Nederlands
mORMot 2 - Pascal Cafe 2025 in NederlandsmORMot 2 - Pascal Cafe 2025 in Nederlands
mORMot 2 - Pascal Cafe 2025 in Nederlands
Arnaud Bouchez
Lecture2_REQUIREMENT_Process__Modelss.pptx
Lecture2_REQUIREMENT_Process__Modelss.pptxLecture2_REQUIREMENT_Process__Modelss.pptx
Lecture2_REQUIREMENT_Process__Modelss.pptx
Aqsa162589
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with EaseCypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Shubham Joshi
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odooTour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
AxisTechnolabs
IObit Driver Booster Pro 12.3.0.557 Free
IObit Driver Booster Pro 12.3.0.557 FreeIObit Driver Booster Pro 12.3.0.557 Free
IObit Driver Booster Pro 12.3.0.557 Free
mohsinrazakpa95
ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]
umeerbinfaizan
New-4K Video Downloader Crack + License Key 2025
New-4K Video Downloader Crack + License Key 2025New-4K Video Downloader Crack + License Key 2025
New-4K Video Downloader Crack + License Key 2025
abbaskanju3
Autodesk MotionBuilder 2026 Free Download
Autodesk MotionBuilder 2026 Free DownloadAutodesk MotionBuilder 2026 Free Download
Autodesk MotionBuilder 2026 Free Download
blouch52kp
Marketo User Group - Singapore - April 2025
Marketo User Group - Singapore - April 2025Marketo User Group - Singapore - April 2025
Marketo User Group - Singapore - April 2025
BradBedford3
TVersity Pro Media Server Free CRACK Download
TVersity Pro Media Server Free CRACK DownloadTVersity Pro Media Server Free CRACK Download
TVersity Pro Media Server Free CRACK Download
mohsinrazakpa43
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlanMaximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
OnePlan Solutions
Managing Changing Data with FME Part 1 - Compare & Detect
Managing Changing Data with FME Part 1 - Compare & DetectManaging Changing Data with FME Part 1 - Compare & Detect
Managing Changing Data with FME Part 1 - Compare & Detect
Safe Software
ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025
umeerbinfaizan
Internet Download Manager Crack Latest version 2025
Internet Download Manager  Crack Latest version 2025Internet Download Manager  Crack Latest version 2025
Internet Download Manager Crack Latest version 2025
mohsinrazakpa26
Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)
blouch36kp
Digital Application Development Services
Digital Application Development ServicesDigital Application Development Services
Digital Application Development Services
daavishenry
Byteexpo Call Center - Presentation.pptx
Byteexpo Call Center - Presentation.pptxByteexpo Call Center - Presentation.pptx
Byteexpo Call Center - Presentation.pptx
hmk11790
Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...
Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...
Migrating GitHub Actions with Nested Virtualization to Cloud Native Ecosystem...
KCD Guadalajara
Virtual DJ Pro Crack 2025 Full Version Download [Latest]
Virtual DJ Pro Crack 2025 Full Version Download [Latest]Virtual DJ Pro Crack 2025 Full Version Download [Latest]
Virtual DJ Pro Crack 2025 Full Version Download [Latest]
umeerbinfaizan
Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]
l07307095
mORMot 2 - Pascal Cafe 2025 in Nederlands
mORMot 2 - Pascal Cafe 2025 in NederlandsmORMot 2 - Pascal Cafe 2025 in Nederlands
mORMot 2 - Pascal Cafe 2025 in Nederlands
Arnaud Bouchez
Lecture2_REQUIREMENT_Process__Modelss.pptx
Lecture2_REQUIREMENT_Process__Modelss.pptxLecture2_REQUIREMENT_Process__Modelss.pptx
Lecture2_REQUIREMENT_Process__Modelss.pptx
Aqsa162589
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with EaseCypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Shubham Joshi
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odooTour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
AxisTechnolabs
IObit Driver Booster Pro 12.3.0.557 Free
IObit Driver Booster Pro 12.3.0.557 FreeIObit Driver Booster Pro 12.3.0.557 Free
IObit Driver Booster Pro 12.3.0.557 Free
mohsinrazakpa95
ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]
umeerbinfaizan
New-4K Video Downloader Crack + License Key 2025
New-4K Video Downloader Crack + License Key 2025New-4K Video Downloader Crack + License Key 2025
New-4K Video Downloader Crack + License Key 2025
abbaskanju3
Autodesk MotionBuilder 2026 Free Download
Autodesk MotionBuilder 2026 Free DownloadAutodesk MotionBuilder 2026 Free Download
Autodesk MotionBuilder 2026 Free Download
blouch52kp
Marketo User Group - Singapore - April 2025
Marketo User Group - Singapore - April 2025Marketo User Group - Singapore - April 2025
Marketo User Group - Singapore - April 2025
BradBedford3
TVersity Pro Media Server Free CRACK Download
TVersity Pro Media Server Free CRACK DownloadTVersity Pro Media Server Free CRACK Download
TVersity Pro Media Server Free CRACK Download
mohsinrazakpa43

Chapter 2 Introduction to C++

  • 1. Chapter 2 Introduction to C++ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda 2-1
  • 2. 2.1 Parts of a C++ Program // sample C++ program #include <iostream> using namespace std; int main() { cout << "Hello, there!"; return 0; } 2-2 comment preprocessor directive which namespace to use beginning of function named main beginning of block for main output statement send 0 back to operating system end of block for main
  • 3. Special Characters (pg. 30) 2-3 Character Name Description // Double Slash Begins a comment # Pound Sign Begins preprocessor directive < > Open, Close Brackets Encloses filename used in #include directive ( ) Open, Close Parentheses Used with function & other times { } Open, Close Braces Encloses a group of statements " " Open, Close Quote Marks Encloses string of characters ; Semicolon Ends a programming statement
  • 4. Important Details C++ is case-sensitive. Uppercase & lowercase characters are different characters. Main is not the same as main. Every { must have a corresponding }, and vice-versa. Watch for the NOTE and WARNING boxes n your text. They provide good information! 2-4
  • 5. 2.2 The cout Object Displays information on computer screen Equivalent to print to screen Use << to send information to cout cout << "Hello, there!"; Can use << to send multiple items to cout cout << "Hello, " << "there!"; Or equivalently cout << "Hello, "; cout << "there!"; 2-5
  • 6. cout << stream insertion operator Must be between each different element cout << Total is << Tot; Total is 49 2-6
  • 7. Starting a New Line To get multiple lines of output on screen - Use endl cout << "Hello, there!" << endl; - Use n in an output string cout << "Hello, there!n"; 2-7
  • 8. New lines of output endl a command Causes a new line of output Dumps the output buffer to output file n a special character Causes a new line of output only MUST be inside quotes Side-effect: when used with file output, some output may not get printed Test question 2-8
  • 9. Common Escape Sequences (p.35) ~~ MUST be contained in quotes ~~ Considered a single character n Newline t Tab a Alarm b Backspace r Return (same line) Prints 1 Prints single quote Prints double quote 2-9
  • 10. Examples cout << Hellon Mary; Hello Mary Note: the single space in front of Mary 2-10
  • 11. 2.3 The #include Directive Inserts the contents of another file into the program Is a preprocessor directive Not part of the C++ language Not seen by compiler Example: #include <iostream> There will be several different files that we will include for different purposes. 2-11 No semicolon; goes here
  • 12. 2.4 Standard & Pre-standard C++ Older-style C++ programs Use .h at end of header files #include <iostream.h> Do not use using namespace convention May not compile with a standard C++ compiler We WILL NOT use the .h format. 2-12
  • 13. 2.5 Variables, Constants, & the Assignment Statement Variable Has a name (identifier) & a type of data it can hold char letter; Is used to reference a location in memory where a value can be stored Must be defined before it can be used The value that is stored can be changed, i.e., it can vary When use name in program, referring to data stored in the corresponding memory location. 2-13 variable name data type
  • 14. Variables Represents a location in memory Stores/Holds on data value If a new value is stored in the variable, it replaces previous value The previous value is overwritten and can no longer be retrieved int age; age = 17; // age is 17 cout << age; // Displays 17 age = 18; // Now age is 18 cout << age; // Displays 18 2-14
  • 15. Assignment Statement Uses the = operator (is assigned) Has single variable on left side and a value or expression on right side Copies the value on right into the variable on left, i.e. its memory location item = 12; total = 15 + 2; tax = Bal * 0.0825; 2-15
  • 16. Constant Data item whose value does not change during program execution NEVER Is also called a literal 'A' // character constant "Hello" // string literal 12 // integer constant 3.14 // floating-point constant Often a test question 2-16
  • 17. 2.6 Identifiers Programmer-chosen names to represent parts of program, such as variables & constants Any length, but you must type it repeatedly Name indicates use of the identifier Cannot use C++ key words as identifiers See Table 2.4 pg. 41 Legal form (this is a question on test 1) Must begin with alphabetic character or _ followed by alphabetic, numeric, or _ . Alpha may be upper- or lowercase 2-17
  • 18. Valid and Invalid Identifiers 2-18 IDENTIFIER VALID? REASON IF INVALID totalSales Yes total_Sales Yes total.Sales No Cannot contain period 4thQtrSales No Cannot begin with digit totalSale$ No Cannot contain $
  • 19. 2.7 Integer Data Types Designed to hold whole numbers Can be signed or unsigned 12 -6 +3 Available in different sizes (i.e., number of bytes): short, int, and long size of short size of int size of long Table 2-6 pg. 44 2-19
  • 20. Defining Variables Variables of the same type can be defined - In separate statements int length; int width; - In the same statement int length, width; Variables of different types must be defined in separate statements int length; short width; 2-20
  • 21. 2.8 The char Data Type Used to hold single characters Or very small integer values: 0 to 15 *but dont* (Usually) Occupies 1 byte of memory A numeric code representing the character is stored in memory 2-21 SOURCE CODE MEMORY char letter = c'; letter 0110 0011
  • 22. String Constant Can be stored a series of characters in consecutive memory locations "Hello" Stored with null terminator, 0, at end Is comprised of characters between the " " 2-22 H e l l o 0
  • 23. A character or a string constant? A character constant is a single character, enclosed in single quotes: 'C' A string constant is a sequence of characters enclosed in double quotes: "Hello, there!" A single character in double quotes is a string constant, not a character constant: "C" 2-23
  • 24. 2.9 The C++ string Class Must #include <string> to create & use string objects Can define string variables in programs string name; Can assign values to string variables with assignment operator name = "George"; Can display with cout cout << name; Note: # include <string> unnecessary if using only string literals cout << George; 2-24
  • 25. 2.10 Floating-Point Data Types Hold real numbers 12.45 -3.8 Stored in form similar to scientific notation Numbers are all signed Types are float - 4 bytes double 8 bytes long double 8 bytes (usually) 2-25
  • 26. Floating Point Examples float Item, Tax; Item = 5.34; Tax = Item * 0.0825; cout << Item << << Tax; ---------------------- 5.34 0.44055 Note: w/o spaces in quotes 5.340.44055 2-26
  • 27. Floating-point Constants Can be represented in - Fixed point (decimal) notation: 31.4159 0.0000625 - E-notation: (we wont use but need to recognize) 3.14159E1 6.25e-5 Usually indicate extremely large or small value Are double by default 2-27
  • 28. Assigning Floating-point Values to Integer Variables If floating-point value is assigned to an integer variable The fractional part will be truncated (i.e., chopped off & discarded) The value is NOT rounded int rainfall = 3.88; cout << rainfall; // Displays 3 2-28
  • 29. 2.11 The bool Data Type Represents values that are true or false bool values are stored as short integers false is represented by 0, true by 1 bool allDone = true; bool finished = false; Note: Any non-zero value is considered true. 2-29 allDone finished 1 0
  • 30. 2.12 Determining the Size of a Data Type The sizeof operator gives size of any data type or variable double amount; cout << "A float is stored in " << sizeof(float) << " bytesn"; cout << "Variable amount is stored in " << sizeof(amount) << " bytesn"; 2-30
  • 31. 2.13 More on Variable Assignments and Initialization Assigning value to a variable Assigns a value to a previously created variable A single variable name must appear on left side of the = symbol int size; size = 5; // legal 5 = size; // not legal 2-31
  • 32. Variable Assignment vs. Initialization Initializing a variable Gives initial value to variable at time it is created Can initialize some or all variables of definition int length = 12; int width = 7, height = 5, area; 2-32
  • 33. What if a variable is not initialized?? double amount; cout << amount; What happens?? . It depends *Ignore - continues, repeats message *Abort program stops *Retry tries again then stops - get MS send error report? 2-33
  • 34. 2.14 Scope The scope of a variable is that part of the program where the variable may be used Scope of variable begins with definition, continues through the block in which it is defined A variable cannot be used before it is defined int a; cin >> a; // legal cin >> b; // illegal int b; (Test question) 2-34
  • 35. Scope To avoid problems Define ALL variables & constants at the beginning of the program!!! Later we will discuss other issues related to scope. 2-35
  • 36. 2.15 Arithmetic Operators Used for performing numeric calculations C++ has unary, binary, and ternary operators unary (1 operand) -5 binary (2 operands) 13 - 7 ternary (3 operands) exp1 ? exp2 : exp3 2-36
  • 37. Binary Arithmetic Operators 2-37 SYMBOL OPERATION EXAMPLE ans + addition ans = 7 + 3; 10 - subtraction ans = 7 - 3; 4 * multiplication ans = 7 * 3; 21 / division ans = 7 / 3; 2 % modulus ans = 7 % 3; 1 Order of operation is standard mathematics.
  • 38. / Operator C++ division operator (/)performs integer division if both operands are integers cout << 13 / 5; // displays 2 cout << 2 / 4; // displays 0 If either operand is floating-point, the result is floating-point cout << 13 / 5.0; // displays 2.6 cout << 2.0 / 4; // displays 0.5 2-38
  • 39. % Operator - Modulus Same priority as * and / C++ modulus operator (%) computes the remainder resulting from integer division cout << 9 % 2; // displays 1 % requires integers for both operands cout << 9 % 2.0; // error 2-39
  • 40. 2.16 Comments Used to document parts of program Written for persons reading source code of program Indicate purpose of program Describe use of variables Explain complex sections of code Ignored by compiler REQUIRED for all programs (by RH) No absolute rules, but STANDARDS 2-40
  • 41. Single-Line Comments Begin with // through to the end of line int length = 12; // length in inches int width = 15; // width in inches int area; // calculated area // Calculate rectangle area area = length * width; 2-41
  • 42. Multi-Line Comments Begin with /* & end with */ Can span multiple lines /*---------------------------- Here's a multi-line comment ----------------------------*/ Can be used as single-line comments int area; /* Calculated area */ MUST have both 2-42
  • 43. Comment Guidelines Use your textbook as a GOOD Example Always comment with name, project name, project description at beginning of every program Descriptive comments within body of program are REQUIRED If comment is so generic it could be moved to any other program then it is not a good comment If comment states exactly what the codes says then it is not a good comment 2-43
  • 44. Chapter 2 Homework Checkpoints These are at the end of most sections (e.g. page 31). You should do all of these End of Chapter questions Page 70+; All (1 27) 8E Quizzes will usually come from checkpoints & end of chapter questions 2-44

Editor's Notes

  • #3: See pr2-01.cpp
  • #5: See pr2-02.cpp and pr 2-03.cpp
  • #7: See pr2-04.cpp, pr2-05.cpp, and pr2-06.cpp
  • #14: See pr2-07.cpp
  • #16: See pr2-08.cpp
  • #20: See pr2-09.cpp and pr2-10.cpp
  • #21: See pr2-11.cpp, pr2-12.cpp, and pr2-13.cpp
  • #24: See pr2-14.cpp
  • #25: See pr2-15.cpp
  • #29: See pr2-16.cpp
  • #30: See pr2-17.cpp
  • #32: See pr2-18.cpp
  • #34: See pr2-19.cpp
  • #37: See pr2-20.cpp
  • #41: See pr2-21.cpp