Title: Alternate Version of STARTING OUT WITH C 4th Edition
1Alternate Version of STARTING OUT WITH C 4th
Edition
- Chapter 3
- Expressions and Interactivity
2 The cin Object
- Standard input object
- Like cout, requires iostream file
- Used to read input from keyboard
- Often used with cout to display a user prompt
first - Data is retrieved from cin with gtgt
- Input data is stored in one or more variables
3The cin Object
- User input goes from keyboard to the input
buffer, where it is stored as characters - cin converts the data to the type that matches
the variable - int height
- cout ltlt "How tall is the room? "
- cin gtgt height
4The cin Object
- Can be used to input multiple values
- cin gtgt height gtgt width
- Multiple values from keyboard must be separated
by spaces or Enter - Order is important first value entered is stored
in first variable, etc.
5Mathematical Expressions
- An expression can be a constant, a variable, or a
combination of constants and variables combined
with operators - Can create complex expressions using multiple
mathematical operators - Example mathematical expressions
- 2
- height
- a b / c
6Using Mathematical Expressions
- Can be used in assignment statements, with cout,
and in other types of statements - Examples
- area 2 PI radius
- cout ltlt "border is " ltlt 2(lw)
7Order of Operations
- In an expression with gt 1 operator, evaluate in
this order - - (unary negation) in order, left to right
- / in order, left to right
- - in order, left to right
- In the expression 2 2 2 2 ,
Do first
Do next
Do last
8Associativity of Operators
- - (unary negation) associates right to left
- / - all associate left to right
- parentheses ( ) can be used to override the order
of operations - 2 2 2 2 4
- (2 2) 2 2 6
- 2 2 (2 2) 2
- (2 2) (2 2) 0
9Algebraic Expressions
- Multiplication requires an operator
- Area lw is written as Area l w
- There is no exponentiation operator
- Area s2 is written as Area pow(s, 2)
- Parentheses may be needed to maintain order of
operations - is written as
- m (y2-y1)/(x2-x1)
10 Implicit Type Conversion
- Operations are performed between operands of the
same type - If not of the same type, C will automatically
convert one to be the type of the other - This can impact the results of calculations
11Hierarchy of Data Types
- Highest
- Lowest
- Ranked by largest number they can hold
long double double float unsigned
long long unsigned int int
12Type Coercion
- Coercion automatic conversion of an operand to
another data type - Promotion converts to a higher type
- Demotion converts to a lower type
13Coercion Rules
- 1) char, short, unsigned short are automatically
promoted to int - When operating on values of different data types,
the lower one is promoted to the type of the
higher one. - When using the operator, the type of
- expression on right will be converted to
type of variable on left
14 Explicit Type Conversion
- Also called type casting
- Used for manual data type conversion
- Format
- static_castlttypegt(expression)
- Example
- cout ltlt static_castltchargt(65)
- // Displays A
15More Type Casting Examples
- char ch 'C'
- cout ltlt ch ltlt " is stored as "
- ltlt static_castltintgt(ch)
- cartons static_castltintgt(eggs/12)
- avg static_castltfloatgt(sum)/count
-
16 Overflow and Underflow
- Occurs when assigning a value that is too large
(overflow) or too small (underflow) to be held in
a variable - Variable contains value that is wrapped around
the set of possible values
17Overflow Example
- // Create a short int initialized to
- // the largest value it can hold
- short int num 32767
- cout ltlt num // Displays 32767
- num
- cout ltlt num // Displays -32768
18Handling Overflow and Underflow
- Different systems handle the problem differently.
They may - display a warning / error message
- stop the program
- or just continue execution
19 Named Constants
- Also called constant variables
- Variables whose content cannot be changed during
program execution - Used for representing constant values with
descriptive names - const float TAXRATE 0.0675
- const int NUMSTATES 50
- Often named in uppercase letters
20const vs. define
- define
- C-style of naming constants
- define NUMSTATES 50
- Interpreted by pre-processor rather than compiler
- Does not occupy a memory location like a constant
variable defined with const - Instead, causes a textual substitution to occur.
In above example, every occurrence in program of
NUMSTATES will be replaced by 50
21 Multiple Assignment and Combined Assignment
- The assignment operator () can be used gt 1 time
in an expression - x y z 5
- Associates right to left
- x (y (z 5))
22Combined Assignment
- Applies an arithmetic operation to a variable and
assigns the result as the new value of that
variable - Operators - /
- Example
- sum amt is short for sum sum amt
23More Examples
- x 5 means x x 5
- x - 5 means x x 5
- x 5 means x x 5
- x / 5 means x x / 5
- x 5 means x x 5
- The entire right hand side is evaluated before
the - combined assignment operation is done.
- x a b means x x (a b)
24 Formatting Output
- Can control how output displays for numeric and
string data - size
- position
- number of digits
- Requires iomanip header file
25Stream Manipulators
- Used to control features of an output field
- Some affect just the next value displayed
- setw(x) Print in a field at least x spaces wide.
Use more spaces if specified field width is not
big enough.
26Stream Manipulators
- Some affect values until changed again
- fixed Use decimal notation (not E-notation) for
floating-point values. - setprecision(x)
- When used with fixed, print floating-point value
using x digits after the decimal. - Without fixed, print floating-point value using x
significant digits. - showpoint Always print decimal for
floating-point values.
27Manipulator Examples
- const float e 2.718
- float price 25.0 Displays
- cout ltlt setw(8) ltlt e ltlt endl 2.718
- cout ltlt setprecision(2)
- cout ltlt e ltlt endl 2.7
- cout ltlt fixed ltlt e ltlt endl 2.72
- cout ltlt setw(6) ltlt price 18.00
28 Working with Characters and String Objects
- char holds a single character
- string holds a sequence of characters
- Both can be used in assignment statements
- Both can be displayed with cout and ltlt
29Character Input
- Reading in a character
- char ch
- cin gtgt ch // Reads in any non-blank char
- cin.get(ch) // Reads in any char
- cin.ignore() // Skips over next char in
- // the input buffer
30String Input
- Reading in a string object
- string str
- cin gtgt str // Reads in a string
- // with no
blanks - getline(cin, str) // Reads in a string
- // that
may contain - // blanks
31String Operators
- Assigns a value to a string
- string words
- words Tasty
- Joins two strings together
- string s1 hot", s2 "dog"
- string food s1 s2 // food hotdog"
- Concatenates a string onto the end of another
one - words food // words now Tasty hot dog"
32 Using C-Strings
- C-string is stored as an array of characters
- Programmer must indicate maximum number of
characters at definition - char temp5 "Hot"
- NULL character (\0) is placed after final
character to mark the end of the string - Programmer must make sure array is big enough for
desired use temp can hold up to 4 characters
plus the \0.
33C-String Input
- Reading in a C-string
- char Cstr10
- cin gtgt Cstr // Reads in a C-string with no
- // blanks. Will
write past the - // end of the
array if input string - // is too long.
- cin.getline(Cstr, 10)
- // Reads in a
C-string that may - // contain blanks.
Ensures lt 9 - // chars are read
in.
34C-String Initialization vs. Assignment
- A C-string can be initialized at the time of its
creation (just like a string object can) - char month10 April
- However, a C-string cannot later be assigned a
value using the operator you must use the
strcpy() function - char month
- month April // wrong!
- strcpy(month, April) //correct
35More Mathematical Library Functions
- These require cmath header file
- Take double arguments and return a double
- Commonly used functions
abs Absolute value
sin Sine
cos Cosine
tan Tangent
sqrt Square root
log Natural (e) log
36More Mathematical Library Functions
- These require cstdlib header file
- rand
- Returns a random number between 0 and the largest
int the computer holds - With the same seed, will yield same sequence of
numbers each time program is run - srand(x)
- Initializes random number generator with
- unsigned int x
37 Introduction to Files
- Can use a file instead of keyboard for program
input - Can use a file instead of monitor screen for
program output - Files are stored on secondary storage media, such
as disk - They allow data to be retained between program
runs
38What is Needed to Use Files
- Include the fstream header file
- Define a file stream object
- ifstream for input from a file
- ifstream infile
- ofstream for output to a file
- ofstream outfile
39Open the File
- Open the file
- Use the open member function
- infile.open("inventory.dat")
- outfile.open("report.txt")
- Filename may include drive, path info.
- Output file will be created if necessary
existing file will be erased first - Input file must exist for open to work
40Use the File
- Use the file
- Can use output file object and ltlt to send data to
a file - outfile ltlt "Inventory report"
- Can use input file object and gtgt to copy data
from file to variables - infile gtgt partNum
- infile gtgt qtyInStock gtgt qtyOnOrder
41Close the File
- Close the file
- Use the close member function
- infile.close()
- outfile.close()
- Dont wait for operating system to close files at
program end - May be limit on number of open files
- May be buffered output data waiting to be sent to
a file