Você está na página 1de 260

2006 C++ Course Handouts January 2006

C++ Programming and


Computer Science

CIS162
CSC100
Version 17
2006

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 1

First Night Roadmap


Social Amenities
Attendance
Introductions
Discuss Syllabus
Discuss Course Objectives
Make Sure We Are Clear on Assignments
Who Has Computer Access and C++ Compilers
Talk a little About Computers and C++

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 2

Notes: 1
2006 C++ Course Handouts January 2006

Subject Overview

C++ Programming.
This course includes features to construct C++ programs and
functions. Topics discussed will be data types, functions, pointers,
input/output routines, structures and disk access routines. Also
discussed are inheritance, encapsulation, classes, members and
overloading. Prerequisites: CIS152 or CIS155 or CIS156 or CIS157
or CIS158 or CIS102.

This is one of the most important and dynamic computer science


subjects taught today. C++ language is used to develop operating
systems, applications and programming tools. In fact, C++ is used
to actually write other compilers such a C, Ada, COBOL and
FORTRAN. This class will take a journey down the path of C++
programming. Additionally, we will discuss other popular related
software and computer science topics. Upon completion of this
course, you will have a crisp outlook and keen understanding of the
computer language of choice in today’s world of computer science.
Sound Exciting? Let’s go.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 3

Course Objectives
1. Explain the history of C++ and basic computer components
2. Describe the software development process
3. Use predefined data types to declare and manipulate variables and
arrays
4. Use operators in arithmetic and Boolean expressions
5. Design and develop structured/modular programs using various flow
control structures and functions
6. Describe object-oriented concepts
7. Design and develop programs using classes and object-oriented
programming techniques
8. Process keyboard input and console output
9. Debug simple and complex programming errors
10. Use standard preprocessor commands
11. Understand the concepts used in the construction of C++ programs,
12. Understand and implement most C++ functions
13. Understand basic structured programming concepts
14. Understand encapsulation, inheritance, scope and overloading
15. Improve your critical thinking skills
16. Understand the relationship between high-level, low-level and
machine languages
17. Understand bit-wise manipulation of data
18. Understand data conversions from binary, decimal and hexidecimal

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 4

Notes: 2
2006 C++ Course Handouts January 2006

An Excellent Text
Starting out with C++,
Alternate Version
4th Edition.
Tony Gaddis, Judy Walters
and Godfrey Muganda

Supplemental Text Books

Problem Solving with C++. Savitch.


C++ Programming: From Problem Analysis to
Program Design. Malik.
Visual C++ .NET. Deitel.
C++ Primer Plus. Stephen Prata.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 5

Grading Policy

100% - 90% A
89% - 80% B
79% - 70% C
69% - 60% D
Below 60 Ooops

Grading Policy
Assignments are presented with the intent of reinforcing the
reading material and topics discussed in the classroom.
Late assignments are welcome, but receive a 10 percent
reduction for each week they are late. All external class
assignments are expected to be typed.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 6

Notes: 3
2006 C++ Course Handouts January 2006

Student Deliverables
Assignment or Activity Percent
Homework 32% (32 x 1 % each)
Midterm Exam 24 %
Final Celebration 24 %
Critical Thinking Paper 5%
Quiz-1 6%
Quiz-2 6%
Attendance 3%
Total 100 %
Extra Credit Papers 5%
All sorts of ways to get an “A”

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 7

How To Calculate Your Grade


Assignment or Activity Percent Actual Extended
Midterm Exam 24% x 90% = .2160
Homework 32% x 94% = .3008
Critical Thinking Paper 5% x 95% = .0475
Final Celebration 24% x 80% = .1920
Quiz-1 6% x 100% = .0600
Quiz-2 6% x 60% = .0360
Attendance 3% x 100% = .0300

Total .8823
Extra Credit Paper 5% x 90% = .0450
Grand Total .9273 (92.73%)

Example-1

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 8

Notes: 4
2006 C++ Course Handouts January 2006

How To Calculate Your Grade


Assignment or Activity Percent Actual Extended
Midterm Exam 24% x 90% = .2160
Homework 32% x 88% = .2816
Critical Thinking Paper 5% x 95% = .0475
Final Celebration 24% x 80% = .1920
Quiz-1 6% x 80% = .0480
Quiz-2 6% x 60% = .0360
Attendance 3% x 75% = .0225

Total .8436
Extra Credit Paper 5% x 90% = .0450
Grand Total .8886 (88.86%)

Example-2

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 9

Course Road Map


Class-1 January 20
In Class: Plan on covering the course syllabus, grading, homework
projects and some basic computer terminology. We will
discuss where C++ is used, how memory is laid out as well
as compilers and interpreters.
Reading: Read Chapter 1 and begin reading chapter 2 in the C++ text
book by Tony Gaddis.
Deliverables: Review and familiarize yourself with this course and
homework roadmap. Be thinking about a topic for your term
paper.
Lab Work: None.
Tests: None.

See Course Map Details, Pages MAP-1 through MAP-13


View Homework Projects
Online C++ Tutorial

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 10

Notes: 5
2006 C++ Course Handouts January 2006

Course Road Map

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 11

College Calendar

SPRING SEMESTER - 2006


Sat Jan 14 Classes Begin
Mon Jan 16 Observance of M L King Birthday
Mon Feb 20 Observance of Presidents' Day
Fri Mar 3 Last Day for Withdrawal without Instructor's Signature
Mon-Sun Mar 13-19 Spring Break
Mon Apr 24 Last Day Student Initiated Withdrawal Accepted
Sun May 7 Last Day of Regular Classes
Mon-Thu May 8-11 **Final Exams
Fri May 12 Commencement
Fri May 12 Spring Semester Ends
Mon May 29 Observance of Memorial Day

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 12

Notes: 6
2006 C++ Course Handouts January 2006

Class Structure
Structure of the Class
Discussions Each Class Night
¾ Roughly 2 hours per night of discussion /dialog

C++ and Software Engineering


Software Development and Methodologies
Computer Technology
Encryption & Decryption Techniques
Careers in IT, Business
Ethics in the Computer Industry
Lab Work
¾ Roughly 1 hour per night

¾ 32 Programming Exercises

¾ Home or the School Labs

Class and Group Activities


¾ C++ Expert Panel Discussions

¾ Student Teach Back Assignments

¾ In-Class Group Assignments

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 13

Grading Standards For C++ Programs

C++ Homework Standards for Each


Program
Header Comments 5%
Other Comments 5%
Screen Shot of Output 5%
Indentation and Style 5%
On time 10%
C++ Code to achieve the result 70%

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 14

Notes: 7
2006 C++ Course Handouts January 2006

Critical Thinking Term Paper

Critical Thinking Term Paper


Five pages, double spaced, cover page, references.

Topics to Choose From


¾ Implementing C++ functions and templates

¾ or

¾ All About C++ Classes and Structures

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 15

Grading Standards For Term Papers

Term Paper
Cover Page 5%
References 5%
Grammar 5%
Spelling 5%
Length 5%
Margins 5%
Page Numbers, Dates, Headings 5%
Content 65%

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 16

Notes: 8
2006 C++ Course Handouts January 2006

Teaching Philosophy

I am here to teach, you're here to learn


I believe if you apply yourself to the
discussions and exercises you can learn this
material, easily.
I believe in respect for the student
I believe in respect for the technology

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 17

How We Learn
We will proceed through many different learning methods

¾ Lectures
¾ Dialogs
¾ Discussions
¾ Presentations
¾ Student Teach-Back
¾ Group Collaboration
¾ Writing
¾ Debates
¾ Practice by Doing C++ in Class
¾ Practice by Doing C++ at Home
¾ Email Activities
¾ Researching Topics
¾ Have Some Fun, too

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 18

Notes: 9
2006 C++ Course Handouts January 2006

Outcomes and Assessments


Statement Regarding Outcomes and Assessment
The faculty and programs at CGCC are dedicated to
effective teaching and successful learning with
emphasis in the following areas: reading, speaking,
listening, writing, mathematics, science, computer
application skills, humanities, problem-solving,
information literacy, critical thinking, and personal
development.

Periodically, students will participate in formal and


informal assessment activities that will help faculty
improve programs and teaching strategies. These
activities are designed to facilitate student growth in
whatever combination of the above outcomes applies
to a course.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 19

Students with Disabilities

Statement Regarding Students with Disabilities


Students with disabilities are required to register for services in
the Disability Resources and Services (DRS) office in the
Student Center at the beginning of the semester. Do not wait
to visit the DRS office if you want support with any CGCC
classes.
The DRS office will meet with you to determine accommodations
based on appropriate documentation. This must be on file
before any accommodation will be provided to students. You
can contact the DRS office at (480)857-5188.

Faculty are not authorized to provide any accommodations nor


can they approve any accommodations for students in this
class

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 20

Notes: 10
2006 C++ Course Handouts January 2006

Leaning Center

Information on Learning Center Services

The CGCC Learning Center's mission is to support students'


academic learning by providing free tutoring and resources
to reinforce and supplement classroom instruction and to
assist CGCC students to achieve academic success. Free
tutoring services are available for many CGCC courses. The
Learning Center is located on the second floor of the Library,
rooms L227, L228, and L229. The Center also provides
instructional support resources in the form of videotapes,
software, and print materials. For a schedule of tutoring
hours, additional information or assistance contact the
Learning Center at (480) 732-7231, or visit our website at:
http://www.cgc.maricopa.edu/lc

Online C++ Tutorial

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 21

Plagiarism

Statement Concerning Plagiarism


Plagiarism is defined as presenting the work of another as one's
own. More than four consecutive words from a source other
than the writer constitute plagiarism when the source is not
clearly identified in appropriate documentation format.

From the CGCC Student Handbook:


"Plagiarism includes, but is not limited to, the use of paraphrase
or direct quotation, of the published or unpublished work of
another person without full and clear acknowledgement. It
also includes the unacknowledged use of materials prepared
by another person or agency engaged in the selling of term
papers or other academic materials."

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 22

Notes: 11
2006 C++ Course Handouts January 2006

Instructor Contact Information


Jim Adams
Work: (480) 929-9803
Email (Work): jima.adams@us.nestle.com
Email (Home): jimadams@softwaredynamix.com
Web Page: www.softwaredynamix.com/javashop/index.php

Software Engineer 25+ years


Teaching since 1996 (C++, Java, Statistics, VB, COBOL)
Developed code using C, C++, FORTRAN, COBOL, Java,
Assembler, VB, C#, PHP, PERL
BS in Engineering, Mathematics Major
MBA Technology Management
MS Systems and Software Engineering

Division Secretary: Carlene Weberg (480) 732-7043

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 23

Web Page

URL is:
www.softwaredynamix.com/javashop/index.php
Contains lots of C++ related information
Syllabus and Course Objectives
Online Midterm and Final Exams
Sample C++ Code
Homework Problems
Contact Information
Previous Test Scores

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 24

Notes: 12
2006 C++ Course Handouts January 2006

Now, I Need Some Information..

On the 3x5 cards, write:

1. Name
2. Phone
3. Email Address
4. Where You Work
5. Hobbies or Interests

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 25

Syllabus Summary

Text Books
Homework & Lab Time
Attendance
Class Structure
Grading
C++ Compilers
Instructor Contact Information
Upon completion of this course, you will have
a crisp outlook and keen understanding of the
computer language of choice in today’s world
of computer science
Sound Exciting? Let’s Learn C++…

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 26

Notes: 13
2006 C++ Course Handouts January 2006

Chapter 1

Introduction to C++, Computer Systems and Problem


Solving
Computer Systems
Hardware, Software
Compilers
Generations of Computers
Algorithms
Software Life Cycle
Origins of C++
Types of Programming Errors
Sample C++ Programs
Problem Solving

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 27

Questions to Think About

What is Computer memory?


How is it organized?
What is it made of?
What do we use it for?
What types of things are stored there?
What is a Program?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 28

Notes: 14
2006 C++ Course Handouts January 2006

Computer Systems

These are all things


you can touch—
CPU Output hardware types of
Input things. They send

Devices Devices data to the CPU and


they take
information from the

Scanners, CRT CPU. Hence the


phrase, Input,
Modems Modems Process, Output, or
MIDI Devices MIDI Devices IPO.

Zip Drives, Main Zip Drives, Software is used to


Jazz Drives, Memory Jazz Drives, control these devices.
Tape Drives Tape Drives C++ is the language
Disk Drives of choice in
Disk Drives RAM managing and
Keyboard Printers controlling hardware
devices.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 29

Computer Systems

Input Hardware Bus size


CPU determines C++ memory
access size

Bus

Output

ALU Main
Memory
Primary Storage
Hardware Disk
Secondary
Registers Storage

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 30

Notes: 15
2006 C++ Course Handouts January 2006

Computer Memory Layout

Base Address,
say, 8000 Relative Address

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D

E a c h b y t e h a s

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 31

Units of Measure

Binary 1 bit, either zero or one


Bits Bunches of zeros & ones
Nibble 4 bits (1/2 byte)
Bytes 8 bits (1 character)
Words 16, 32 or 64 bits (Machine Dependent)
Kilobytes KB 1024 bytes
Megabytes MB 1 million bytes
Gigabytes GB 1 billion bytes
Terabytes TB 1 trillion bytes

Milli, Micro, Nano, Pico .001, .000001, .000000001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 32

Notes: 16
2006 C++ Course Handouts January 2006

History of C and C++

Ken Thompson and Dennis Ritchie in 1972


Started out on UNIX
BCPL or B language (Used for O/S’s)
They were looking for a clever way to build systems
software without using Assembler
Today, C is on every platform, imaginable
C, C++, Visual C++, Advanced C
¾ Who knows the difference between system software
and application software?

A high-level programming language developed by Bjarne


Stroustrup at Bell Labs. C++ adds object-oriented features
to its predecessor, C. C++ is one of the most popular
programming language for graphical applications, such as
those that run in Windows and Macintosh environments

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 33

Where Is C++ Used?

Sequential, Linear Applications


Event Driven Applications
System software
¾ Operating systems, DOS, sorts, utilities
¾ Analogous to heart and lungs
Tools
¾ Compilers, Data Utilities, (Copies, Sorts, Finds, etc)
Robotics
¾ Pick & Place, Industrial Robotics
Game Software
Embedded Systems (Who can give an example?)
Communication Software
¾ Netscape, Internet Explorer, Modem-based Software, Printer
Drivers, Communications Drivers
Application software
¾ Accounts Payable, Payroll, Inventory, Sales Analysis,
Marketing, etc

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 34

Notes: 17
2006 C++ Course Handouts January 2006

C++ is Powerful and Flexible


C++ has useful functions for implementing control
systems and operating systems
Great for building stacks, queues, linked-lists
Fairly readable code
Excellent for reusable functions
Very Portable
¾ Can move source code from UNIX to PC to
Mainframe very easily
¾ If one stays within the confines of ANSI C
¾ American National Standards Institute (ANSI)
Powerful and flexible

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 35

C++ is Programmer Oriented

Programmer oriented
¾ Access to memory locations

¾ Bit manipulations

¾ Robust set of operators (+, -, /, *, |, &&, etc)

¾ Character oriented

¾ Not very strict with respect to data types

Pascal is very strict, for example


Easy to make mistakes, but, you can do most
everything imaginable
Good News: You can do anything with C++
Bad News: You can do anything with C++

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 36

Notes: 18
2006 C++ Course Handouts January 2006

Steps in Program Development

Questions to Think About


1. What steps do you think we use to create a C++
program?
2. Are there any formal methodologies?
3. What are CASE tools?
4. Can paper and pencil be of any value in this
computer programming world?
5. What is Software Engineering?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 37

Steps in Program Development

Define objectives
Preliminary design (Flow Chart Perhaps)
Write the code (Implies some kind of editor)
Compile & link
Run the program Process O nline
D isplay

Test and debug Storage

Maintain and modify


Manual
Document Decision Tape
Opera tion

Off-Page
Input Connect Predefine
Output or d Process

Today, we tend to use an iterative approach

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 38

Notes: 19
2006 C++ Course Handouts January 2006

Flowcharting
Start

Entity Relationship Diagrams


Open
File
State Transition Diagrams
Flow Charts
Read a
Byte

Print
Byte

No
EOF

Yes
Close
File Stop

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 39

Developing a Solid Program

Break the program up into sections such as


reading input
displaying output
processing of some kind

Design functions to be called that do specifically what is


needed and to be very focused on what is to be done.
reading_input()
display_headings()
print_detail()
accumulate_totals()
calculate_mean()
process_nc_data()
attach_to_host()
reverse_string()

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 40

Notes: 20
2006 C++ Course Handouts January 2006

Systems Development Life Cycle

Preliminary Investigation

Maintenance

Systems Analysis

Implementation Systems Design

Systems Development
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 41

Another Development Methodology


A. Conceptual Design Phase -- During the conceptual design phase, agency
management identifies the need for a system, and develops a high level
project plan.
B. Planning Phase -- During the planning phase, system developers and
users determine functional, quality, and architecture requirements of the
system identified in the conceptual design phase, design the system to
meet those requirements, and plan for development and implementation.
C. Development Phase -- During the development phase, system developers
code and test the system designed in the planning phase, and prepare for
training and implementation.
D. Implementation Phase -- During the implementation phase, users learn
and test the system to ensure it meets their requirements. If the users
accept the system, systems developers install and convert to the new
system.
E. Post Implementation/System Support Phase -- During the post
implementation/system support phase, management, users, and systems
developers continuously monitor the implemented system to ensure it
measures up to the expectations and requirements developed in previous
phases, and to enhance the system as needed to increase the system's
useful life.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 42

Notes: 21
2006 C++ Course Handouts January 2006

Problem Solving Technique


Break Down the Problem into its component
parts
¾ Input
¾ Processing
¾ Output
Very popular in programming and technology
Sometimes it’s helpful to start with the Output
¾ Screen layout, report layout, etc

Desk checking
Manual testing with sample data
Quality assurance (QA)
Walk through
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 43

Algorithms

Like a recipe
Same as
¾ Directions
¾ Methods
¾ Procedures
An algorithm is a sequence of precise instructions
that leads to a solution
We’ll use the word “algorithm” a lot in this class
Sorting, searching, etc
Payroll applications have many algorithms,
¾ Bonus calculations, pay calculations, tax calculations

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 44

Notes: 22
2006 C++ Course Handouts January 2006

Chapter 1 Summary

Introduction to Computer & Programming

Computer Systems Homework:


Compilers 1. Read Chapter 1 and 2 in the text
book
Algorithms 2. Install C++ Compiler
Software Life Cycle 3. Type in some of the sample C++
Origins of C++ programs in chapter 1
Types of Programming Errors 4. Start Critical Thinking Paper
Sample C++ Programs

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 45

Chapter 2

Introduction to C++

Variables
Assignment Statements
Declarations
cout
#include directives
Escape Sequences
Data Types
Arithmetic Operators
Simple Flow Control
Programming Style

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 46

Notes: 23
2006 C++ Course Handouts January 2006

What is Binary?

Binary Numbering System


00000001 1
00000010 2
00000011 3
00000100 4 Look at the supplemental
00000101 5 information in the last
00000110 6 chapter of this handout..
00000111 7
00001000 8
00001001 9
00001010 10
00001011 11

11111111 255

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 47

Mechanics of Binary?

Mechanics of Number Systems

Decimal Number System


123410=1x103+2x102+3x101+4x100

Binary Number System


10012=1x23 + 0x22 + 0x21 + 1x20
Any number to the 0th power is 1
Any number to the 1st power is the number
itself

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 48

Notes: 24
2006 C++ Course Handouts January 2006

First Generation Programs--Binary

0100 1001 49 First there was actual binary.


Then there was hex as a
0100 0101 45 shorthand notation
0011 1001 39
0111 0010 72 Take 01001001 as an example

0011 1110 3E 0100 1001

0000 0000 00 4 9 in hex

1011 0011 B3 01 001 001


1110 1111 EF 1 1 1 in octal
1010 1010 AA each of which is 73
0101 0101 55
0000 1111 0F
0001 1110 1E

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 49

Second Generation Programs--Assembler

Address Inst Mnemonic


0110 0100 00100100 org $100
0110 0101 00100010 mov 0, r1
0110 0110 00011100 add 10, r1
0110 0111 00111001 sto r1, counter
0110 1000 00011111 ret
0110 1001 00000000 counter
end

We wanted an easier way to get to machine code


from some type of human readable code.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 50

Notes: 25
2006 C++ Course Handouts January 2006

Third Generation—FORTRAN,COBOL, C, etc


INTEGER FACTORIAL PROCEDURE DIVISION.
DO N=1,12
WRITE (6,*) N,' factorial is Begin.
',FACTORIAL (N) DISPLAY "Enter student details using
END DO template below".
END
DISPLAY "Enter -
OPTIONS /RECURSIVE ID,Surname,Initials,CourseCode,Gender"
INTEGER FUNCTION FACTORIAL (N) DISPLAY "SSSSSSSNNNNNNNNIICCCCG".
!
! The Factorial of an integer N is N * N-1 * ACCEPT StudentDetails.
N-2 ... * 1.
! passing N-1 to perform the calculation. ACCEPT CurrentDate FROM DATE YYYYMMDD.
Note that ACCEPT DayOfYear FROM DAY YYYYDDD.
! each recursive call to FACTORIAL will get
its own ACCEPT CurrentTime FROM TIME.
! copy of N.
DISPLAY "Name is ", Initials SPACE Surname.
!
! If N is 1 or less, the result is 1. (We DISPLAY "Date is " CurrentDay SPACE
assume that CurrentMonth SPACE CurrentYear.
IF (N .GT. 1) THEN
FACTORIAL = FACTORIAL(N-1) * N DISPLAY "Today is day " YearDay " of the
ELSE year".
FACTORIAL = 1 DISPLAY "The time is " CurrentHour ":"
END IF CurrentMinute.

RETURN STOP RUN.


END

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 51

Fourth Generation Programs


C++, Java, SQL, VB

#include <iostream>
using namespace std;

main()
{
cout << “This is a simple C++ Program “ << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 52

Notes: 26
2006 C++ Course Handouts January 2006

Sample C++ Program

#include <iostream>
using namespace std;

void main()
{
int length, width, area;
cout << "Calculate the area of a rectangle \n\n";
cout << "Enter Length:";
cin >> length;
cout << "Enter width:";
cin >> width;

area = length * width;

cout << "Area of the rectangle is " << area;


cout << "\n\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 53

Basic C++ Construction

#include <iostream> Include directive


using namespace std;

int main()
{
variable declarations
Main Body
C++ statements
return(0);
}

Return statement

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 54

Notes: 27
2006 C++ Course Handouts January 2006

Use of Semicolons

All C++ statements, except function


definitions, end with a semicolon ;

int x = 100;
cost = 100.99;
cout << “This is C++ at its finest \n”;
display_text(x);
return(0);
printf(“C++ is Very Cool..”);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 55

Code Blocks & White Space

Code Blocks
Braces
{
Marks the begin and end of
a block of code
}

White Space

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 56

Notes: 28
2006 C++ Course Handouts January 2006

Code Blocks & White Space

C++ code fragment shown earlier can be written like this:


#include <iostream>
using namespace std;
void main () {
cout << "This is a simple C++ Program";
cout << "\n"; }

Can also be written like this:


#include <iostream>
using namespace std;
void main ()

cout << "This is a simple C++ Program";


cout << "\n";

}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 57

Syntax v. Semantic Errors

Syntax or Compile Time errors are caused by uncertain coding that


the compiler cannot understand. Sometimes called Semantic
errors.
cout << “Test Text;

Run Time errors cause a program to stop or halt abruptly.


z = 0;
x = y / z;

Logic errors cause some erroneous action to be taken


int x=10;
cout << “X cubed is:“ << x*x;

if (sales_amount > 1.00) then sales_tax = 0

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 58

Notes: 29
2006 C++ Course Handouts January 2006

Compilers

As you might guess,


Compilers are extremely complex pieces of
software
Compilers must parse each line of source
code
¾ Called a translation unit
detect syntax errors
generate variable space in the symbol table
generate assembler code equivalent to the C
code
assemble the assembler code into object code
links object code into an executable file .EXE

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 59

Source, Object and Executable

C++ is the Source Code


Compiler converts to an Object module
The Linker converts the object module to
an Executable
C++ Source Compile Object Linker .EXE

User types in
C++ Source
Code

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 60

Notes: 30
2006 C++ Course Handouts January 2006

Compile and Build Process


1. Look at the Problem you need to solve
2. Design with paper and pencil the input, process and
output
3. Open the IDE (MS or Borland for example)
4. Type in your C++ code
5. Compile it (F7 on MS)
6. Fix Errors
7. Run the Program

Compiler creates several files


1. C++ Source (You type this in)
2. .exe file
3. .dsp files
4. .ncb files
5. .prj files
6. .opt files
7. .plg files

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 61

How to Print Results

1. Click the upper left corner


2. Choose “Edit” then “Mark”
3. Select the text you want to print
4. Click the upper left corner, again
5. Select “Edit” and then “Copy”
6. Copy and paste to MS Word or
back into the compiled source
code

1. Click the upper left corner


2. Choose “Edit” then “Mark”
3. Select the text you want to print
4. Click the upper left corner, again
5. Select “Edit” and then “Copy”
6. Copy and paste to MS Word or back into the compiled source code

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 62

Notes: 31
2006 C++ Course Handouts January 2006

C++ Keywords and Variables

Questions
1. Who can discuss the difference
between a keyword and a variable?
2. What is a C++ Comment?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 63

C++ Keywords
1. asm 21. for 41.struct
2. auto 22. friend 42.switch
3. break 23. goto 43.template
4. bool 24. if 44.this
5. case 25. inline 45.throw
6. catch 26. int 46.true
7. char 27. long 47.try
8. class 28. mutable 48.typedef
9. const 29. namespace 49.typeid
10. continue 30. new 50.typename
11. default 31. operator 51.union
12. delete 32. private 52.unsigned
13. do 33. protected 53.using
14. double 34. public 54.virtual
15. else 35. register 55.void
16. enum 36. return 56.volatile
17. extern 37. short 57.while
18. explicit 38. signed
19. false 39. sizeof
20. float 40. static

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 64

Notes: 32
2006 C++ Course Handouts January 2006

Tokens

Smallest source-code element


recognized by the compiler
¾ keywords
¾ identifiers
¾ constants
¾ strings
¾ operators
¾ punctuator

int counter=0;
counter++;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 65

Special Characters in C++

Char Name Description


// double slash beginning of comment
# pound sign preprocessor directives
<> less than/greater set wrap file names in include statements
<< double less than used on cout object
>> double greater than used on cin object
() parenthesis used in functions for passing arguments
[] brackets used for array subscript notation
{} braces marks beginning and end of code block
“ “ quotes used to designate a quoted string
; semicolon C++ statement termination character

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 66

Notes: 33
2006 C++ Course Handouts January 2006

Five Type of Statements in C++

¾ Null Statements (Comments)


¾ Declaration Statements
¾ Assignment Statements
¾ Control Statements
¾ Functions

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 67

Comments in C++
// C++ Comments
// Continue until the end of line

x = 100; // comments can go here

// ;-------------------------------------
// ; Comments about a section of code
// ;-------------------------------------
x = q;
y= x / 12.2 * (x * 1.223);
/* standard C comment text */

x = 700; /* comments can go here */

/* ;-------------------------------------
; Comments about a section of code
;------------------------------------- */
x = q;
Y = x / 12.2 * (x * 1.223);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 68

Notes: 34
2006 C++ Course Handouts January 2006

Comments in any program


/* ;----------------------------------------------------------;
; Program Name: Problem 3.21 ;
; File: HW3_21.cpp ;
; Description: Brief description of what ;
; the program does ;
; Author: Jim Adams ;
; Environment: MS C++ 6.00 ;
;----------------------------------------------------------; */

Or
// ;----------------------------------------------------------;
// ; Program Name: Problem 3.21 ;
// ; File: HW3_21.cpp ;
// ; Description: Brief description of what ;
// ; the program does ;
// ; Author: Jim Adams ;
// ; Environment: DEV C++ 4.9 ;
// ;----------------------------------------------------------;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 69

What Is a Variable

A Variable is place in computer memory where we store


information used in our programs.
For example, say we have a program where we prompt the
user for name, address, city state and zip.
We use Variables to store this information for later use.
The contents of a variable are just that—variable.
Your computer's memory can be viewed as a series of
cubbyholes. Each cubbyhole is one of many, many such holes
all lined up. Each cubbyhole or memory location is numbered
sequentially. These numbers are known as memory
addresses. A variable reserves one or more cubbyholes in
which you may store a value.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 70

Notes: 35
2006 C++ Course Handouts January 2006

What Is a Variable
A Variable is place in computer memory where we
store information used in our programs.
Each data variable has three components
¾ Its Name,
¾ Its Value,
¾ Its Type

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 71

Variable Declaration
All variables must be declared before they are used
Syntax
Type_Name Variable_Name_1, Variable_Name_2, Variable_Name_n;
Type_Name Variable_Name=initial_value;
Type_Name Variable_Name(initial value);

Examples
int result,
count,
age,
length,
myVariable;
int accum=0;
int counter(0);
char StatusByte;
float cost_of_goods_sold;
double national_debt=0.0;
bool complete;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 72

Notes: 36
2006 C++ Course Handouts January 2006

Variable Declaration

Variable Name Choice


¾ up to 31 characters (ANSI Standard)
¾ lowercase & uppercase
¾ underscore character
¾ variables must begin with a letter or the
underscore character

Microsoft allows 247 characters

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 73

Variable Declaration
Each variable takes a certain amount of memory space
depending on the type of compiler

int count; // 2 bytes internally


int i;

char ch=‘A’; // 1 byte internally


char status;

float cost; // 4 bytes internally


float vector;

double nations_debt; // 8 bytes internally


double sum;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 74

Notes: 37
2006 C++ Course Handouts January 2006

Variable Declaration

Names you supply for variable types of


information
We Declare Variables
More Examples:
int result;
int count;

Variables (identifiers) are case sensitive


int Adder;
int adder; // these are different

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 75

Meaningful Variable Names

Use Meaningful Names

x = y * z;

distance = speed * time;


tax = cost * tax_rate;
Voltage = Amperes * Resistance;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 76

Notes: 38
2006 C++ Course Handouts January 2006

Meaningful Variable Names


Declaring a Variable
Stay clear of variables with names like: J23qrsnf, xyz, Mary.
Good variable names tell you what the variables are for; using good
names makes it easier to understand the flow of your program.
The following statement defines an integer variable called myAge:

int myAge; // called Camel Case

As a general programming practice, avoid such horrific names as


J23qrsnf, and restrict single-letter variable names (such as x or i)
to variables that are used only very briefly. Try to use expressive
names such as myAge or howMany. Such names are easier to
understand three weeks later when you are scratching your head
trying to figure out what you meant when you wrote that line of
code.
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 77

Valid Variable Declarations


Valid Variable Names
deposit
end_bal
withdrawal
continue_process
ResultField
Result
AnnualSalary
CostOfGoodsSold
Selling_Price
quantity_on_hand

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 78

Notes: 39
2006 C++ Course Handouts January 2006

Invalid Variable Declarations


Invalid Variable Names
2002DepositAmount
end bal
withdrawal.amt
continue
char
cout
int
Result-Field
1selling_price
$cost

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 79

Data Types

Character Data Types


char stores a single character
string stores a series of characters
Integral Data Types
long stores large integers
int -3, -2, -1, 0, 1, 2, 3, 4, 5, etc
short
Fractional Data Types
float numbers like 3.14159
double numbers like 3.141598658934569876542301
Logical Data Types
bool true or false

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 80

Notes: 40
2006 C++ Course Handouts January 2006

Data Types

Type Specifiers Type Modifiers


int 16 bits
long 32 bits unsigned
short 8 bits signed
char 8 bits
float 32 bits
double 64 bits
bool 8 bits
string N/A

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 81

Variable Data Types


Type Size Values
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
unsigned short int 1 byte 0 to 255
short int 1 byte -127 to 127
unsigned long int 4 bytes 0 to 4,294,967,295
long int 4 bytes -2,147,483,648 to 2,147,483,647
char 1 byte 256 character values
float 4 bytes -3.4e-38 to +3,4e38
double 8 bytes -1.7e-308 to +1.7e308
bool 1 byte true or false

Note: The sizes of variables might be different from those shown in


above, depending on the compiler and the computer you are using. If
your computer had the same output as was presented above, then this
should apply to your compiler. If your output was different, you should
consult your compiler's manual for the values that your variable types
can hold.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 82

Notes: 41
2006 C++ Course Handouts January 2006

Integer Data Types


short 0111 1111
unsigned short 1111 1111
int 0111 1111 1111 1111
unsigned int 1111 1111 1111 1111
long 0111 1111 1111 1111 1111 1111 1111 1111
unsigned long 1111 1111 1111 1111 1111 1111 1111 1111

Sign Bit
Signed means you can have both positive and
negative values. The high-order bit, the sign bit, is
used to denote negativity.
Unsigned means you can store only positive values.
The sign bit is used for data not a sign.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 83

Size of an Integer
Size of Integers
On any one computer, each variable type takes up a
single unchanging amount of room. That is, an integer
might be two bytes on one machine, and four on another,
but on either computer it is always the same, day in and
day out.
A char variable (used to hold characters) is most often
one byte long. A short integer is two bytes on most
computers, a long integer is usually four bytes, and an
integer (without the keyword short or long) can be two
or four bytes.
A character is a single letter, number or symbol that
takes up one byte of memory.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 84

Notes: 42
2006 C++ Course Handouts January 2006

Integer Use Example


#include <iostream>
using namespace std; Our checking balance is -2500 dollars
We drove 4276 miles
void main() We flew 186650 days to get to Saturn
{
int checking;
unsigned int miles_driven;
long days;

checking = -2500;
miles_driven = 4276;
days = 186650;

cout << “Checking balance " << checking << " dollars" << endl;
cout << "We drove " << miles_driven << “ miles” << endl;
cout << "We flew " << days << " days to get to Saturn\n\n\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 85

Overflow and Underflow


What happens when a numeric variable reaches maximum /
minimum values for a given data type

Integer with 32767 and 1 is added gives -32768


because the sign bit is set and all other bits are zero

Underflow is a maximum negative number going positive, so, -


32768 minus 1 = +32767

0111 1111 1111 1111

+ 0000 0000 0000 0001


1000 0000 0000 0000

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 86

Notes: 43
2006 C++ Course Handouts January 2006

Break

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 87

char and string Data Types


char 0000 0000 through 1111 1111
string Any number of bytes

On some systems a character data variable is


two bytes.
Holds values like ‘A’, ‘B’, ‘$’
char ch;
char status_byte=‘ ‘;
string first_name=“Santa”;
string last_name=“Claus”;
string movie_title=“The Good, The Bad, The Ugly.”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 88

Notes: 44
2006 C++ Course Handouts January 2006

Using Character Variables


#include <iostream>
using namespace std;

void main(void) A = 01000001 Generated


{ Output
char letter;
A
letter=65; B
cout << letter << endl; B= 01000010 Z
letter=66;
cout << letter << endl;
letter=90;
cout << letter << endl << endl;
A
B
letter='A';
Z
cout << letter << endl;
letter='B';
cout << letter << endl;
letter='Z';
cout << letter << endl; Code Verified 03/19/2003
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 89

String Variable Declaration


String Data Type
string myName;
string yourName;
string bookTitle;
string Inventory_Item_Description;

Same as
char myName[30];
char yourName[30]; An Array of
char bookTitle[45]; Characters
char Inventory_Item_Description[60];

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 90

Notes: 45
2006 C++ Course Handouts January 2006

Using String Variables


#include <iostream>
#include <string>
using namespace std;

void main()
Generated Output
{ Ada Lovelace
string myName; Sally Ride
string yourName; Ada LovelaceSally Ride
string bothNames;

myName =“Ada Lovelace";


yourName ="Sally Ride";
bothNames =myName;
bothNames.append(yourName); // More on this later

cout << myName << endl;


cout << yourName << endl;
cout << bothNames << endl; Code Verified 04/29/2003
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 91

Floating Point Data Types


float 4 bytes
double 8 bytes
long double 8 bytes. Some use 10 or 16 bytes

IEEE 754-1985 governs binary floating-point arithmetic. It specifies


number formats, basic operations, conversions, and
exceptional conditions. The related standard IEEE 854-1987
generalizes 754 to cover decimal arithmetic as well as binary.
bits 0-22 are fraction (mantissa)
bits 23-30 are the exponent
bit 31 is the sign bit
http://www.nuvisionmiami.com/books/asm/workbook/floating_tut.htm

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 92

Notes: 46
2006 C++ Course Handouts January 2006

Floating Point Data Types

float 4 bytes
double 8 bytes
long double 8 bytes. Some use 10 or 16 bytes

float Range is -1.2e-38 to 3.4e38


double Range is -2.2e-308 to 1.8e308

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 93

Boolean Variable Declaration


Boolean Data Type
bool a_switch;
bool status_byte=true;
bool We_Are_Finished=false;
bool We_Have_Data;
bool x;

Generally used to make C++ programs more


readable.
do
{
c++ statements
}
while (We_Have_Data);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 94

Notes: 47
2006 C++ Course Handouts January 2006

Boolean Variable Declaration


#include <iostream>
using namespace std; Generated
Output
void main()
{ 0
bool are_we_finished; 1

are_we_finished = false;
cout << are_we_finished << "\n\n";

are_we_finished = true;
cout << are_we_finished << "\n\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 95

Type Specifier Examples


int x;
unsigned int y;
signed int distance;
float cost;
short int counter;
long big_counter;
unsigned long HugeCounter;
double mass_of_sun;
char ch;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 96

Notes: 48
2006 C++ Course Handouts January 2006

Equivalents

Type Specifier Same As


signed int int or signed
unsigned int unsigned
signed char char
unsigned char no equivalent
short int short or signed short
signed long int long or signed long

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 97

Simple Arrays

char name[5] = “TEST “;


char address[25]=“”;
char response[4]=“YES”;
char myArr[20];
char buffer[1000];
int arr[100];
float costs[1000];

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 98

Notes: 49
2006 C++ Course Handouts January 2006

Internal Data Representation

Say, we have the following variable declarations

int x = 100;
char ch = ‘A’;
char name[4] = “TEST“;
short int counter = 1;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 99

Internally, Looks Like This . . . .

100 A T E S T 1

00000000 01100100 01000001 01010100 01000101 01010011 01010100 00000001


---- 2 bytes ------ -1 byte- ---------------- 4 bytes ------------------ 1 byte

See Appendix-A, page 1121 in the text for all ASCII


Characters

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 100

Notes: 50
2006 C++ Course Handouts January 2006

ASCII v. Numeric

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 101

Assignment Statements

We assign values to the declared variables

Syntax:
Variable = Expression

Simple Examples:
x = 1;
a = x * 100;
b = 0;
ch = ‘A’;
z = (d/2) + 40;
cost = 154.90;
mass = 300000;
Distance_to_Moon = 210000;
counter = counter + 1;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 102

Notes: 51
2006 C++ Course Handouts January 2006

Assignment Statements

Variable Initialization is Important in C++

Simple Examples: Initialized at compile time


int x = 1;
int count = 0;
char ch = ' ';
float cost = 0.0;
double mass(0.0);

int main()
{
x = 1; Initialized at run time
count = 0;
mass = 0.0;
cost = 0.0;
ch = ' ';
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 103

Assignment Statements

Multiple Assignments
An unusual feature of C++ is the fact that an
assignment statement also has a value.
The value of the assignment statement can
itself be assigned to another variable. For
example, the statement a = 77 has a value
of 77. So we can have
b = a = 77; // both variables take the value 77

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 104

Notes: 52
2006 C++ Course Handouts January 2006

The Beginning of Every C++ Program

#include <iostream>
using namespace std;

Or

#include <iostream.h>

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 105

The cout Object

cout (character out)

Syntax
cout << variable-1 << variable-2 << text-1 << text-2;

Examples
int input_number=1000;
cout << “Enter a number less than 100”;
cout << “Number entered is ” << input_number << endl;
cout << “Press Enter \n”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 106

Notes: 53
2006 C++ Course Handouts January 2006

The cout Object

Examples
cout << “This is a test”;

cout << “This “


<< “is “
<< “a “
<< “test “;

cout << “This is a test \n\n\n”;


cout << “This is a test” << endl << endl << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 107

The endl Object

endl stands for “End of Line”


Pronounced “end-ell”

We also use the “backslash n” to


accomplish the same effect
cout << “\n”;
cout << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 108

Notes: 54
2006 C++ Course Handouts January 2006

More Detailed Escape Sequences

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 109

#define -- preprocessor command


#define
preprocessor command
used for defining constants

Examples:
#define PI 3.14159
#define GRAVITY 32.2
#define LF 10
#define CR 13

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 110

Notes: 55
2006 C++ Course Handouts January 2006

#define -- preprocessor command


#include <iostream>
using namespace std;
#define PI 3.14159 Generated Output
#define MAX 5
Circumference is 32.9867
float diameter=10.5; Where Pi is 3.14159 and diameter is 10.5
float circumference=0.0;

void main(void)
{
circumference = diameter * PI;
cout << "Circumference is " << circumference << endl;
cout << "Where Pi is "
<< PI
<< " and diameter is "
<< diameter
<< endl;
cout << MAX;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 111

#define -- preprocessor command


#include <iostream>
using namespace std;
#define begin {
#define end }
#define display cout <<
#define read_screen cin >>
#define program int main(void)

int age; Can actually define


your own language
program
begin
display "Enter your age:";
read_screen age;
end

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 112

Notes: 56
2006 C++ Course Handouts January 2006

#define -- preprocessor command


#include <iostream.h> Standard C++
#include <ctype.h> Character Handling
#include <math.h> Math and Trig Functions
#include <stdlib.h> General Utilities
#include <stdio.h> Basic Input & Output
#include <errno.h> Error Handling
#include <fstream.h> C++ File I/O
#include <string.h> String Handling
#include <time.h> Date and Time Structures
#include <signal.h> Signal Handling

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 113

Chapter 2 Summary

Introduction to C++
Variables
Assignment Statement
Declarations
cout
Escape Sequences
Formatting Numbers
Data Types
Various Operators
Programming Style

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 114

Notes: 57
2006 C++ Course Handouts January 2006

Chapter 3

C++ Console Interaction

Cin
I/O Manipulators
Printing Hex and Octal
Operators
Expressions

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 115

cin Object

cin (character in)


Syntax
cin >> variable-1 >> variable-2 >>. . . ;

Examples
cin >> number1;
cin >> mass_of_sun >> distance_from_earth;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 116

Notes: 58
2006 C++ Course Handouts January 2006

cin Object
#include <iostream>
using namespace std;

void main()
{
Enter an integer, a float and a character:
1234 1234.456 B
int whole; Whole Number is:1234
float fraction; Fractional Number is:1234.46
char letter; Letter Entered is: B

cout << "Enter an integer, a float and a character:";


cin >> whole >> fraction >> letter;

cout << " Whole Number is:" << whole << endl;
cout << "Fractional Number is:" << fraction << endl;
cout << " Letter Entered is:" << letter << endl;

} // end of main

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 117

Inputting a String (using char)


// Also known as C-Strings
#include <iostream> cout and cin
#include <string> are Objects
using namespace std;

void main()
{ Member
char fullname[50]; Function

cout << "Enter your full name: ";


cin.getline(fullname, 50);

cout << fullname << endl;


}
Enter your full name: Samuel F.
B. Morse
Samuel F. B. Morse

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 118

Notes: 59
2006 C++ Course Handouts January 2006

Inputting a String (using string)


#include <iostream>
#include <string>
using namespace std;

void main()
{
string st;

cout << "Enter your full name:";


getline(cin, st);
cin object
cout << st << endl;
}
Enter your full name: Samuel F.
B. Morse

Samuel F. B. Morse

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 119

Stream I/O Library Header Files

Note: There is no “.h” on standard header files.


Be careful about “using namespace std”

iostream -- contains basic information required for all


stream I/O operations
iomanip -- contains information useful for performing
formatted I/O with parameterized stream manipulators
fstream -- contains information for performing file I/O
operations
strstream -- contains information for performing in-memory
I/O operations (i.e., into or from strings in memory)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 120

Notes: 60
2006 C++ Course Handouts January 2006

I/O Manipulators
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(4);

Sets the precision and attributes to be used on


subsequent cout and other I/O functions
setf attributes
ios::fixed // don’t use scientific notation
ios::scientific // use scientific notation
ios::showpoint // always show a decimal point
ios::noshowpoint // do not show a decimal point
ios::showpos // show a plus on positive
ios::noshowpos // show a plus on positive
ios::right // right justify
ios::left // left justify

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 121

Classes for Stream I/O in C++

ios is the base class.


istream and ostream inherited from ios
ifstream inherits from istream (and ios)
ofstream inherits from ostream (and ios)
iostream inherits from istream and ostream (& ios)
fstream inherits from ifstream, iostream, and ofstream

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 122

Notes: 61
2006 C++ Course Handouts January 2006

C++ Stream I/O -- Stream Manipulators


C++ provides various stream manipulators that
perform formatting tasks.
Stream manipulators are defined in <iomanip>
These manipulators provide capabilities for
¾ setting field widths,
¾ setting precision,
¾ setting and unsetting format flags,
¾ flushing streams,
¾ inserting a "newline" and flushing output stream,
¾ skipping whitespace in input stream

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 123

I/O Manipulator Summary


There are several other manipulators that can be inserted into an output stream
(on many systems you will have to use #include <iomanip.h> to use these)

dec Use decimal base


oct Use octal base
hex Use hex base
endl End of line
ends End of string ('\0')
right force right justification
left force left justification
fixed Fixed point
showpoint Show the decimal point
flush Flush output buffer
setw(w) Set output width to w (0 is default)
setfill(c) Set fill character to c (blank is default)
setprecision(p) Set float precision to p
Boolalpha Use strings true and false
noboolalpha Use numeric 0 and 1 for boolean
uppercase
nouppercase
skipws Skip white space on input
noskipws Don’t skip white space on input

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 124

Notes: 62
2006 C++ Course Handouts January 2006

I/O Manipulator Example


#include <iostream>
using namespace std;

void main ()
{
cout.setf ( ios_base::hex, ios_base::basefield ); // set hex as the basefield
cout.setf ( ios_base::showbase ); // activate showbase
cout << 700 << endl;
cout << 255 << endl; Output
cout.unsetf ( ios_base::hex ); // deactivate hex 0x2bc
cout.setf ( ios_base::oct ); // activate octal 0xff
cout << 700 << endl;
cout << 255 << endl;
01274
0377
cout.unsetf ( ios_base::oct ); // deactivate hex
cout.unsetf ( ios_base::showbase ); // deactivate showbase 700
cout << 700 << endl;
cout << 255 << endl; 255
}

Code tested 10/28/2002

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 125

setprecision() Example
#include <iostream> 1234.123400
#include <iomanip> 1234.12340
using namespace std; 1234.1234
1234.123
void main() 1234.12
{ 1234.1
double cost=1234.1234; 1234

cout << fixed << setprecision(6) << cost << endl;


cout << fixed << setprecision(5) << cost << endl;
cout << fixed << setprecision(4) << cost << endl;
cout << fixed << setprecision(3) << cost << endl;
cout << fixed << setprecision(2) << cost << endl;
cout << fixed << setprecision(1) << cost << endl;
cout << fixed << setprecision(0) << cost << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 126

Notes: 63
2006 C++ Course Handouts January 2006

I/O Manipulator setw() Example


1.12
#include <iostream> 1.12
#include <iomanip> 1.12
using namespace std; 1.12
1.12
void main() 1.12
{ 1.12
double cost=1.12;

cout << fixed << setprecision(2);


cout << setw(9) << cost << endl;
cout << setw(8) << cost << endl;
cout << setw(7) << cost << endl;
cout << setw(6) << cost << endl;
cout << setw(5) << cost << endl;
cout << setw(4) << cost << endl;
cout << setw(3) << cost << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 127

Using the IO Manipulators


#include <iostream>
#include <iomanip>
using namespace std; Output
00700
void main () 00255
{ 002bc
cout << setfill('0'); 000ff
cout << setw(5) << 700 << endl; 01274
cout << setw(5) << 255 << endl; 00377

// print the numbers in hexidecimal format


cout << setw(5) << hex << 700 << endl;
cout << setw(5) << hex << 255 << endl;

// print the numbers in octal format


cout << setw(5) << oct << 700 << endl;
cout << setw(5) << oct << 255 << endl;
} Code tested 05/12/2003

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 128

Notes: 64
2006 C++ Course Handouts January 2006

Printing HEX & Octal


Output
[***192]
#include <iostream> [****c0]
#include <iomanip>
using namespace std; [***300]
[***192]
// Start of main logic section
3.1416
void main(void)
{
int num=192;
cout << "[" << setw (6) << setfill('*') << num << "]" << endl;
cout << hex << "[" << setw (6) << setfill('*') << num << "]" << endl;
cout << oct << "[" << setw (6) << setfill('*') << num << "]" << endl;
cout << dec << "[" << setw (6) << setfill('*') << num << "]" << endl;
cout << setprecision(4) << 3.14159 << endl;
cout << flush;
} Validated 7/13/2001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 129

Let’s See What We Know!


#include <iostream>
#include <iomanip>
using namespace std;

void main()
{
double x;
double y;
double value;

// Get The User Input


cout << "Enter a number:"; Generated Output
cin >> x;
cout << "Enter another number:"; Enter a number:123.33
cin >> y; Enter another number:432.44
value = (x * y) + x; Values Entered: 123.3300 432.4400
Final Value: 53456.1552
// Output Section One
cout << "Values Entered: "
<< fixed
<< setprecision(4)
<< setw(11)
<< x
<< setw(11)
<< y
<< endl; Code Verified 05/03/2003
cout << "Final Value: " << value << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 130

Notes: 65
2006 C++ Course Handouts January 2006

sizeof() Operator
sizeof() operator
Used to obtain the size of any particular data type
Examples:
#include <iostream>
Size of an Integer is: 2
using namespace std;
Size of a Long is: 4
void main() Size of a Short is: 1
{ Size of a Float is: 4
int s; Size of a Double is: 8
char ch; Size of a char is: 1
float cost_of_goods;
double mass_of_the_earth;
long distance;

s = sizeof(float);
cout << "Size of an Integer is: “ << sizeof(int) << endl;
cout << " Size of a Long is: “ << sizeof(distance) << endl;
cout << " Size of a Short is: “ << sizeof(short) << endl;
cout << " Size of a Float is: “ << sizeof(cost_of_goods)<< endl;
cout << " Size of a Double is: “ << sizeof(double) << endl;
cout << " Size of a char is: “ << sizeof(char) << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 131

Operator Precedence

( ) Parentheses
- + ++ -- Unary Operators
* / % Multiply, Divide, Modulo
+ - Plus, Minus
< > <= >= Greater-Than, Less-Than
== != Equal to, Not Equal to
&& And
|| Or
= Set

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 132

Notes: 66
2006 C++ Course Handouts January 2006

Operators & Precedence

Plus, Minus, Multiply, Divide


x = 100; /* set x to 100 */
x = x + 10; /* set x to 110 */
y = x / 2; /* set y to 55 */
z = y * 10; /* set z to 550 */
w = z - 50; /* set w to 500 */
a = ((x + 10) / 2 * 10) - 50;

A word of Caution
butter = 25.0 + 60.0 * n / scale;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 133

Mathematical Expressions

Y = 3X
2

Y = (3 * X) / 2;
Y = (X / 2) * 3;
Y = (3 / 2) * X;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 134

Notes: 67
2006 C++ Course Handouts January 2006

Exponents in C++

y = 9x3+25
y = (9 * pow(x,3)) + 25;

y = (9x3)5
y = pow((9 * pow(x,3)),5);

Exponent Function
y=pow(n, q); // n raised to the power of q

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 135

Some Math Functions in C++

abs y=abs(x); Absolute value


cos y=cos(x); Cosine
log y=log(x); Natural log
log10 y=log10(x); Log base 10
sin y=sin(x); Sine in radians
sqrt y=sqrt(x); Square root
tan y=tan(x); Tangent
pow y=pow(n, q); n to the power of q

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 136

Notes: 68
2006 C++ Course Handouts January 2006

Sine Function in C++


#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.14159
All trig functions in C++
void main() assume radian measure
{
double y, x;
// 57.3248 degrees per radian
y=sin(PI/2); // 90 degrees
cout << y << endl;
y=sin(PI/4); // 45 degrees 1
cout << y << endl; 0.707106
y=sin(PI/2); // 90 degrees 1
cout << y << endl; 0.866025
y=sin(PI/3); // ? 0.500694
cout << y << endl;
y=sin(0.5244); // 30 degrees
cout << y << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 137

strlen() Function
strlen() operator
Used to obtain the size of a string’s contents
#include <iostream>
using namespace std;

void main()
{ Santa Claus
int len; Content Length:11
char myName[30]; String Capacity:30
strcpy(myName, "Santa Claus");
len=strlen(myName);
cout << myName << endl;
cout << " Content Length:" << len << endl;
cout << "String Capacity:" << sizeof(myName) << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 138

Notes: 69
2006 C++ Course Handouts January 2006

Symbolic Constants

Used to guarantee integrity of a variable


READ ONLY Variable
Called A Symbolic Constant

float x = 100.00;
const float PI = 3.14159;
const float SQUARE_ROOT_OF_2 = 1.4142;

int main(void)
{
x = 3 / SQUARE_ROOT_OF_2; // Okay
PI = 3.2; // Not gonna happen
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 139

Literal Constants

Floating Point
Integer
Character

A number, character or string that can


be used as a value in a program.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 140

Notes: 70
2006 C++ Course Handouts January 2006

Floating Point Constants

15.75 // 15.75
1.575E1 // 15.75
1575E-2 // 15.75
-2.5e-3 // -0.0025
25e-4 // 0.0025

All floating point constants are stored as double precision


unless otherwise stated.

110.21F floating point


110.21D double

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 141

Integer Constants

10L Long Constant


79L Long Integer Constant
776745UL Long Unsigned
778866LU Long Unsigned
12345 Typical Integer Constant

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 142

Notes: 71
2006 C++ Course Handouts January 2006

Numeric Constants
Integer constants can be decimal, octal or hexidecimal.
(base 10, 8 & 16)
// Decimal Constants (Base 10)
10
132
32179

// Octal Constants (Base 8)


012
0204
076663

// Hexidecimal Constants (Base 16) Hex for short


0xa or 0XA
0x84
0x7db3

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 143

Character Constants
Used for letters of the alphabet, special characters, etc.
Wrapped in single quotes: ‘a’ ‘B’
Can be escape characters: ‘\n’ ‘\a’
Can be hex or octal escape sequence: ‘\x07’

Examples:
char ch = 'Q';
char_code = '$';

char ch2 = 't';


char ch3 = 116; // 116 is little t
char ch4 = '0x74'; // hex 74 is little t

ch = ‘t’;
ch = 116;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 144

Notes: 72
2006 C++ Course Handouts January 2006

Operators
= Assignment ++ Auto Increment
< less than -- Auto Decrement
<= less than or equal += Increment
== equal to -= Subtract
> greater than *= Multiply
>= greater than or equal /= Divide
!= NOT equal to %= Modulo
~ Compliment % Modulo
| Boolean Or + Add
& Boolean And - Subtract
^ Exclusive Or * Multiply
>> Shift right / Division
<< Shift Left . Dot Operator
&& Logical And :: Scope Resolution
|| Logical Or
! Not Operator

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 145

Incrementing A Variable
The most common value to add (or subtract) and then
reassign into a variable is 1. In C++, increasing a
value by 1 is called incrementing, and decreasing by
1 is called decrementing. There are special operators
to perform these actions

Say we have,
int x=0;

Increment
x=x+1; // Traditional
x+=1; // shorthand for x=x+1
x++; // postfix mode, same as x=x+1
++x; // prefix mode, same as x=x+1

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 146

Notes: 73
2006 C++ Course Handouts January 2006

Decrementing a Variable
The most common value to add (or subtract) and then
reassign into a variable is 1. In C++, increasing a
value by 1 is called incrementing, and decreasing by
1 is called decrementing. There are special operators
to perform these actions

Say we have,
int x=10;

Decrement
x=x-1; // Traditional
x-=1; // shorthand for x=x-1
x--; // postfix mode, same as x=x-1
--x; // prefix mode, same as x=x-1

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 147

Incrementing and Decrementing

Say we have,
int x = 10;

Increment
x=x+5; // Traditional
x+=5; // shorthand for x=x+5

Decrement
x=x-5; // Traditional
x-=5; // shorthand for x=x-5

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 148

Notes: 74
2006 C++ Course Handouts January 2006

Postfix / Prefix Example


#include <iostream>
using namespace std; Code Verified 6/21/2001
int number=2;
int result=0;
main()
{

result = 2*(number++);
cout << "Result using postfix notation:" << result
<< " " << number << endl << endl;

number=2;
result = 2*(++number);
cout << "Result using prefix notation: " << result
<< " " << number << endl;
}

Result using postfix notation:4 3


Result using prefix notation: 6 3

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 149

Short-cut Assignment Operators

scores += 20; same as scores = scores + 20;


dimes -= 2; same as dimes = dimes - 2;
cars *= 4; same as cars = cars * 4;
time /= 2.90;same as time = time / 2.90;
reduce %= 3; same as reduce = reduce % 3;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 150

Notes: 75
2006 C++ Course Handouts January 2006

Type Casting
Sometimes you need to use type casts to tell the compiler to
convert the type of an expression to another type.
For example, suppose that you have the sum of integer values
in an integer variable, and would like to compute the average
and store it in a variable of type float.
In this case, you must tell the compiler to first convert sum to
float before performing the division.
// Older C-style of type casting
int sum, n;
float average;
average = (float) sum / n;

// C++ Style of type casting


float average;
average = float (sum) / n;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 151

Type Casting
The Type Cast Operator

int total=0;
float x=1.6;
float y=1.7;
total = x + y;
If 1.6 + 1.7 = 3.3, then why does total = 3?
total = (int) x + (int) y;
result: total equals 2
because 1.6 converts to integer 1
and 1.7 converts to integer 1
Conversion is done before the addition operation

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 152

Notes: 76
2006 C++ Course Handouts January 2006

Character Constants & Initialization


Output…
char x; Typecast
int main() Operator A 65
{ B 66
x='A';
cout << x++ << " " << (int) x << endl; C 67
cout << x++ << " " << (int) x << endl; D 68
cout << x++ << " " << (int) x << endl; E 69
cout << x++ << " " << (int) x << endl; F 70
cout << x++ << " " << (int) x << endl; G 71
cout << x++ << " " << (int) x << endl;
cout << x++ << " " << (int) x << endl; H 72
cout << x++ << " " << (int) x << endl; I 73
cout << x++ << " " << (int) x << endl; J 74
cout << x++ << " " << (int) x << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 153

Integer Division, Negating, Modulus


Dividing Integers
int x, y, z;
x = 13;
y = 3;
z = x / y; // z will have 4, not 4.3333

Negating a number or variable ( unary )


x = -100; // set x to -100
z = -x; // set z to +100

Modulus Arithmetic
int x, y, z;
x = 13;
y = 3;
z = x % y; // z will have 1, not 4.3333

In other words 13 divided by 3 is 4 with 1 remainder

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 154

Notes: 77
2006 C++ Course Handouts January 2006

Modulus Operator
Modulus Operator: %
The result of the modulus operator (%) is the remainder when the first
operand is divided by the second.

Example

In the following example, the modulus operator is used to determine if


the numeric value 4 evenly divides into nCenturyYear. If the remainder
is zero, the nCenturyYear must be a leap year, so the
LeapYearFunction() is executed.

// Example of the modulus operator


int nCentury;

if ((nCenturyYear % 4) == 0) {
LeapYearFunction();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 155

Modulus Division Example


#include <iostream> Code Verified 09/19/2001
using namespace std;

int main( )
{ Large loop with a display every 10,000
long x;
long rem;
char ch;

for (x=0; x<100000; x++)


{
rem = x % 10000;
if (rem == 0)
cout << "Here we are at " << x << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 156

Notes: 78
2006 C++ Course Handouts January 2006

Review Questions for Chapter 3


1. What’s the largest number one can represent with a signed integer (2 bytes)?
2. What does ‘\n’ mean?
3. How many characters can we use to represent a variable name?
4. The cout object is used to do what?
5. What is wrong with the following C++ statements?
1. cout << This is a test;
2. cout << cost_of_goods_sold
6. What I/O Manipulator can we use to print in hex? Octal?
7. Are the following variable declarations legal?
double 102inventory;
float inventory_102;
character ch;
int cout;
cost float;

1. What is the result of the following code fragment?


1. int number=3;
2. result = 3*(++number);

2. What does the following statement print?


1. int age=32;
2. cout << “My age is: “ << age++;
3. Explain typecasting
4. How do we represent “not equal” in C++?
5. 0x9 is what type of constant?
6. 07 is what type of constant?
7. The cout.precision(2) member function does what?
8. What operators can we use to increment a variable?
9. What is the modulus operator?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 157

Homework
1. Should have read Chapters 1 and 2 by now
2. Read Chapter 3 for next week
3. Work on your term paper
4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 4 on page 161 of the text.
(Chapter 3)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 158

Notes: 79
2006 C++ Course Handouts January 2006

Chapter 3 Summary

Introduction to C++

Variables
Assignment Statement
Declarations
cin
Escape Sequences
Formatting Numbers
Data Types
Various Operators
Programming Style

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 159

Chapter 4

Making Decisions (Selection Structures)

If Statement
If -- Else
Switch Statement
Logical Operators
Expressions
Enumerated Types

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 160

Notes: 80
2006 C++ Course Handouts January 2006

Insight

Computer Science states that a good language


must be able to:
1. Execute a sequence of statements
2. Repeat statements until some condition is met
3. Test and branch between alternative statements

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 161

Logical Operators

Logical Operators
&& And
|| Or
! Not
Produces one of two values, TRUE or FALSE
==
!=
<
<=
>
>= Operate on pairs of built in types

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 162

Notes: 81
2006 C++ Course Handouts January 2006

Expression Examples

Code Fragment Examples

if (x < 100)
if (x > 0)
if (count <= 50)
if (count >= 1000)
if (ch != ‘Z’)
if (status == 1)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 163

If Statement Syntax

Syntax
if (expression)
C++ statement

if (expression)
{
C++ statements
C++ statements
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 164

Notes: 82
2006 C++ Course Handouts January 2006

if statement
Example
int main(void)
{
float cost;
cout << "Enter Product Cost Less than $100.00: ";
cin >> cost;
if (cost > 100.00)
cout << "Cost Entered Exceeded $100.00 " << cost << endl;
}

Code Verified 06/21/2001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 165

Another Example of “if”

int number_in;
int max=0;
int min = 999999;
cout << "Enter a floating point number:";
cin >> number_in;

if (number_in > max)


max = number_in;

if (number_in < min)


min = number_in;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 166

Notes: 83
2006 C++ Course Handouts January 2006

If - else

A Third Example Showing if -- else


if (remainder == 0)
cout << num2 << " is a factor of " << num1 << endl;
else
cout << num2 << " is not a factor of " << num1 << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 167

If Logic is tricky, sometimes …


#include <iostream>
using namespace std;

int main() The order of the logical


{ comparisons is important
int testScore;
char grade;

cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;

if (testScore < 60) Enter your test score and I will tell you
grade = 'F'; the letter grade you earned: 44
if (testScore < 70) Your grade is A.
grade = 'D';
if (testScore < 80)
grade = 'C';
if (testScore < 90)
grade = 'B';
if (testScore <= 100)
grade = 'A'; Verified 11/23/2003

cout << "Your grade is " << grade << ".\n";


}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 168

Notes: 84
2006 C++ Course Handouts January 2006

If Logic is tricky, sometimes …


#include <iostream>
using namespace std;

int main() The order of the logical


{ comparisons is important
int testScore;
char grade;

cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;

if (testScore <= 100) Enter your test score and I will tell you
grade = 'A'; the letter grade you earned: 44
if (testScore < 90) Your grade is F.
grade = 'B';
if (testScore < 80)
grade = 'C';
if (testScore < 70)
grade = 'D';
if (testScore < 60)
grade = 'F'; Verified 11/23/2003

cout << "Your grade is " << grade << ".\n";


}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 169

else if construct
#include <iostream>
using namespace std;

int main()
{ Or, we can use the else-if
int testScore; construct
char grade;
bool goodScore = true;

cout << "Enter your numeric test score and I will\n";


cout << "tell you the letter grade you earned: ";
cin >> testScore;

if (testScore < 60)


grade = 'F';
else if (testScore < 70) Enter your numeric test score and I will
grade = 'D';
else if (testScore < 80) tell you the letter grade you earned: 44
grade = 'C'; Your grade is F.
else if (testScore < 90)
grade = 'B';
else if (testScore <= 100)
grade = 'A';
else
goodScore = false;

if (goodScore)
cout << "Your grade is " << grade << ".\n"; Verified 11/23/2003
else
cout << testScore << " is an invalid score.\n";

}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 170

Notes: 85
2006 C++ Course Handouts January 2006

Else-if Example (1 of 2)
void main()
{
char choice;
int months;
float charges;
cout << " Health Club Membership Menu\n";
cout << "A. Standard Adult Membership\n";
cout << "B. Child Membership\n";
cout << "C. Senior Citizen Membership\n";
cout << "D. Quit the Program\n\n";
cout << "Enter your choice: ";
cin.get(choice);

cout << fixed << showpoint << setprecision(2);

Continued

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 171

Else-if Example (2 of 2)
if (choice < 'A' || choice > 'D')
{ cout << "The valid choices are A through D.\n";
cout << "Run the program again\n";
}
else if (choice == 'A')
{ cout << "For how many months? ";
cin >> months;
charges = months * 40.00;
cout << "The total charges are $" << charges << endl;
}
else if (choice == 'B')
{ cout << "For how many months? ";
cin >> months;
charges = months * 20.00;
cout << "The total charges are $" << charges << endl;
}
else if (choice == 'C')
{ cout << "For how many months? ";
cin >> months;
charges = months * 30.00;
cout << "The total charges are $" << charges << endl;
}
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 172

Notes: 86
2006 C++ Course Handouts January 2006

Nested if statements
void main()
{
char employed, recentGrad;

cout << "Are you employed? (Y or N) ";


cin >> employed;
cout << "Have you graduated from college in the past two years? ";
cin >> recentGrad;

if (employed == 'Y')
{ // Nested if
if (recentGrad == 'Y') // Employed and a recent grad
{
cout << "You qualify for the special interest rate.\n";
}
else // Employed but not a recent grad
{
cout << "You must have graduated from ";
cout << "college in the past two years to qualify.\n";
}
}
else // Not employed
cout << "You must be employed to qualify.\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 173

Nested if statements
if (status == SINGLE)
{
if (income <= SINGLE_CUTOFF1)
tax = RATE1 * income;
else if (income <= SINGLE_CUTOFF2)
tax = SINGLE_BASE2 + RATE2 * (income - SINGLE_CUTOFF1);
else
tax = SINGLE_BASE3 + RATE3 * (income - SINGLE_CUTOFF2);
}
else
{
if (income <= MARRIED_CUTOFF1)
tax = RATE1 * income;
else if (income <= MARRIED_CUTOFF2)
tax = MARRIED_BASE2 + RATE2 * (income - MARRIED_CUTOFF1);
else
tax = MARRIED_BASE3 + RATE3 * (income - MARRIED_CUTOFF2);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 174

Notes: 87
2006 C++ Course Handouts January 2006

Logical Operators (or / and)

Example Showing && and ||


And operator is &&
Or operator is ||

And operator
if (income > 100000 && dependents == 0)
tax_amount = income * 0.33;

Or operator
if (income > 200000 || itemized_deductions > 50000)
call_an_audit = true;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 175

The “AND” Operator


One of the most common mistakes in
programming regardless of the language.
Set y=8

((y<3) && (y>7))

So, 8<3 is false


8>7 is true
We have, (false && true)
False AND True will evaluate to False when using &&

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 176

Notes: 88
2006 C++ Course Handouts January 2006

The “AND” Operator


#include <iostream>
using namespace std;
void main()
{
char employed, recentGrad;
cout << "Are you employed? (Y or N)";
cin >> employed;
cout << "Have you graduated from college ";
cout << "in the past two years? ";
cin >> recentGrad;
if (employed == 'Y‘ && recentGrad == 'Y')
{
cout << "You qualify for the special ";
cout << "interest rate.\n";
}
else
{
cout << "You must be employed and have\n";
cout << "graduated from college in the\n";
cout << "past two years to qualify.\n";
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 177

Logical Or Condition

if ((year == 2000) && (month == 2) && (day == 29))


{
// Do some leap year stuff..
}
Which one is faster ?
if (year == 2000)
if (month == 2)
if (day == 29)
process_leap_year();

Lazy Evaluation of Boolean Operators


Boolean Expressions are interpreted left to right
In an OR condition, scanning stops once a true value is found
In an AND condition, scanning stops once a false value is found

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 178

Notes: 89
2006 C++ Course Handouts January 2006

Logical Or Condition
void main()
{ Making a previous example, better
char employed, recentGrad;

cout << "Are you employed? (Y or N) ";


cin >> employed;
cout << "Have you graduated from college in the past two years? ";
cin >> recentGrad;

if (employed == ‘Y‘ || employed == ‘y‘ )


{
if (recentGrad == ‘Y‘ || recentGrad == ‘y’)
{
cout << "You qualify for the special interest rate.\n";
}
else
{
cout << "You must have graduated from ";
cout << "college in the past two years to qualify.\n";
}
}
else
cout << "You must be employed to qualify.\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 179

The “OR” Operator


Example
Say we have the following expression and y=8

((y<3) || (y>7))

So, 8<3 is false


8>7 is true
We have, (false || true)

False OR True will evaluate to true when using


||

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 180

Notes: 90
2006 C++ Course Handouts January 2006

The “OR” Operator


#include <iostream>
using namespace std;

void main()
{
float income;
int years;

cout << "What is your annual income? ";


cin >> income;
cout << "How many years have you worked at your current job? ";
cin >> years;

if (income >= 35000 || years > 5)


cout << "You qualify.\n";
else
{
cout << "You must earn at least $35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 181

Some Rules
AND Condition
Exp-1 Exp-2 Exp1 && Exp2
True True True
True False False
False True False
False False False

OR Condition
Exp-1 Exp-2 Exp1 || Exp2
True True True
True False True
False True True
False False False

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 182

Notes: 91
2006 C++ Course Handouts January 2006

Some Rules
AND Condition (Multiply)
Exp-1 Exp-2 Exp1 && Exp2
1 1 1
1 0 0
0 1 0
0 0 0

OR Condition (Add)
Exp-1 Exp-2 Exp1 || Exp2
1 1 1
1 0 1
0 1 1
0 0 0
Think of True as 1 and False as 0

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 183

Technical Notes
Logical AND
if ( (x == 5) && (y == 5) )
if ( x == 5 && y == 5 )

Logical OR
if ( (x == 5) || (y == 5) )
if ( x == 5 || y == 5 )

Logical NOT
These are the same
if ( !(x == 5) )
if (x != 5)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 184

Notes: 92
2006 C++ Course Handouts January 2006

Tao of C++

Zero = FALSE, Any other value = TRUE


int x, y, b, c, d;

c=10;
d=2;

x = (c > d);
y = (d == c);
b = (c < 2);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 185

More on Truth in C++

if (value)
cout << “It is True”;

if (x + y)
cout << “It is True”;

if (pow(a, b))
cout << “It is True”;

Zero = FALSE, Any other value = TRUE

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 186

Notes: 93
2006 C++ Course Handouts January 2006

More on Truth in C++

Zero = FALSE, Any other value = TRUE

What Happens Here ??


n = 100;
if (n)
cout << n << endl;

What Happens Here ??


n = 0;
if (n)
cout << n << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 187

Example of TRUE/FALSE
int x, y, z;
main(void)
{
x = 10;
y = 0;
z = -12;
if (x)
cout << "X is True: " << x << endl; // Prints
else
cout << "X is False:" << x << endl;
if (y)
cout << "Y is True: " << y << endl;
else
cout << "Y is False:" << y << endl; // Prints
if (z)
cout << "Z is True: " << z << endl; // Prints
else
cout << "Z is False:" << z << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 188

Notes: 94
2006 C++ Course Handouts January 2006

Not Operator

NOT Operation

Exp !Exp
1 0
0 1

Think of True as 1 and False as 0

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 189

Not Operator
#include <iostream>
using namespace std;

void main()
{
float income;
int years;

cout << "What is your annual income? ";


cin >> income;
cout << "How many years at your current job? ";
cin >> years;
if (!(income >= 35000 || years > 5))
{
cout << "You must earn at least $35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
else
cout << "You qualify.\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 190

Notes: 95
2006 C++ Course Handouts January 2006

De Morgan’s Law
What if..
if (amount > 0 && amount < 1000) …

Now let’s try


if (!(amount > 0 && amount < 1000)) …
When it is NOT true that amount > 0 and amount < 100

Augustus de Morgan (1806-1871) states


!(A && B) is the same as !A || !B
!(A || B) is the same as !A && !B

(A × B) = A + B

(A + B) = A × B

Breeding, Kenneth. (1992). Digital Design Fundamentals.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 191

De Morgan’s Law
Let’s prove it:

a b a+b !(a+b) !a !b a×b


0 0 0 1 1 1 1
0 1 1 0 1 0 0
1 0 1 0 0 1 0
1 1 1 0 0 0 0

How cool is that?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 192

Notes: 96
2006 C++ Course Handouts January 2006

Practice

Say count = 1 and limit = 10, evaluate the


following:

(count == 1) && (limit < 20)


(limit > 20) || (count < 5)
!(count == 12)
(count == 1) && (limit/count > 7)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 193

Practice

What output will be produced by the following code


snippet?
int x = 2;

if (x <= 3)
if (x != 2)
cout << “Hey There \n”;
else
cout << “Go Man Go \n”;
else
cout << “Here we are ! \n”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 194

Notes: 97
2006 C++ Course Handouts January 2006

Common Problem

What output will be produced by


the following code snippet?

w = 1;
if (w = 2)
cout << “w equals 2”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 195

Common Problem

A value lies between 0 and 100


if it is at least 0 and at most 100.

It lies outside the range


if it is less than 0 or greater than 100.

There is no golden rule. You just have to


think carefully

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 196

Notes: 98
2006 C++ Course Handouts January 2006

Common Problem

Dangling else

How would you fix the following code


fragment?

if (richter_value >=0)
if (richter_value <=4)
cout << “Harmless”;
else
cout << “Negative Value is invalid”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 197

Quality Tip

Don’t code like this:

if ((d = b * b - 4 * a * c) >= 0) r = sqrt(d);

if (n-- > 0)
other C++ statements

Do this instead:
d = b * b - 4 * a * c;
if (d >= 0)
r=sqrt(d);

if (n-- > 0)
other C++ statements

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 198

Notes: 99
2006 C++ Course Handouts January 2006

Switch statement
int digit;
switch (digit)
{
case 1: cout << “one”; break;
case 2: cout << “two”; break;
case 3: cout << “three”; break;
case 4: cout << “four”; break;
default: cout << “error”; break;
}

Once a condition is “true” the remaining


statements are executed
Can only be applied to integer and character data
types
Test cases can only be constants
A very common error is to omit the break
statement

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 199

Switch statement
#include <iostream>
using namespace std;
Code Verified 09/20/2001
int main( )
{
char grade;
cout << "Enter your midterm grade and press return: ";
cin >> grade;
switch (grade)
{
case 'A':
cout << "Excellent. "
<< "You need not take the final.\n";
break;
case 'B':
cout << "Very good. ";
cout << "Your midterm grade now is "
<< grade << endl;
break;
case 'C':
cout << "Passing.\n";
break;
case 'D':
case 'F':
cout << "Not good. “ << "Go study.\n";
break;
default:
cout << "That is not a possible grade.\n";
}
cout << "End of program.\n";
return 0;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 200

Notes: 100
2006 C++ Course Handouts January 2006

Switch Statement
#include <iostream>
using namespace std;
int main( )
{ Code Verified 09/19/2001
char ch;

cout << "Enter Menu Option(A-C or X to End):";


cin >> ch;
switch (ch)
{
case 'A' :
cout << "You Chose Menu Item:" << ch << endl;
break;
case 'B' :
cout << "You Chose Menu Item:" << ch << endl;
break;
case 'C' :
cout << "You Chose Menu Item:" << ch << endl;
break;
case 'X' :
break;
default :
cout << "Invalid Menu Choice. No Action Taken:" << ch << endl;
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 201

Code Blocks

if (day == 29)
if (month == 2)
if (year == 2000)
{
total_balance = 0.0;
inventory_quantity = 100;
cout << day << month << year;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 202

Notes: 101
2006 C++ Course Handouts January 2006

Code Blocks

if (day == 29)
if (month == 2)
if (year == 2000)
{
double Monthly_Usage;
long Julian_Date;
Monthly_Usage = consumption * 1.223;
Julian_Date = 23456;
}

Monthly_Usage is known only to the code block


Considered to have Block Scope

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 203

goto statement

Example of goto statement


int x;
int main(void)
{
x = 0;
start:
cout << “Value of x is “ << x << endl;
x++;
if (x < 100)
goto start;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 204

Notes: 102
2006 C++ Course Handouts January 2006

The Conditional Operator

Syntax:
expression ? Expression : expression
a = x > 100 ? 0 : 1;

Is the same as
if (x > 100)
a = 0;
else
a = 1;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 205

The Conditional Operator

Syntax:
expression ? Expression : expression
score = 90;
cout << "Your Grade is " << (score<60 ? "Fail“ : "Passing");

Is the same as
if (score < 60)
cout << "Your Grade is Failing;
else
cout << "Your Grade is Passing;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 206

Notes: 103
2006 C++ Course Handouts January 2006

The Conditional Operator


#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
const float payRate = 50.0;
float hours, charges;

cout << "How many hours were worked? ";


cin >> hours;

hours = hours < 5 ? 5 : hours; // Conditional


operator
charges = payRate * hours;

cout << fixed << showpoint << setprecision(2);


cout << "The charges are $" << charges << endl;
return 0;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 207

Enumerated Types

enum Roster {Tom, Jim, Sharon, George, Carolyn, Bob};

Creates a data type named Roster


// declare a variable of type Roster
Roster student;
if (student == Sharon)
cout << “It’s true”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 208

Notes: 104
2006 C++ Course Handouts January 2006

Enumerated Types

Can declare specific values (Integer only)


enum Dept {factory=11, sales=20, warehouse=49};

enum Colors {red, orange, yellow=9, green, blue};


Assigned Values are: red=0, orange=1, yellow=9,
green=10, blue=11

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 209

Floating Point Round Off Errors


Fact of life when using floating point data
Divide 1 by 3 to two decimals, we get 0.33
Multiply by 3 and we get 0.99, not 1.00
#include <iostream>
using namespace std;

void main()
{
double f= 4.35;
int n = (int)(100 * f);
if (n == 435)
cout << n << "\n";
else
cout << “Something is wrong “ << n << endl;
}

Prints
Something is wrong 434

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 210

Notes: 105
2006 C++ Course Handouts January 2006

Floating Point Round Off Errors


#include <iostream>
#include <iomanip>
using namespace std;

void main()
{
double a=6 * 0.666666;
if (a == 4.0)
cout << "Hit"; // not true

cout << setprecision(12) << a << "\n\n";


}
Prints: 3.999996
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 211

Random Number Generator

#include <iostream> // has cout stuff


#include <stdlib.h> // Has srand function
#include <time.h> // has time functions
using namespace std;

void main( void )


{
cout << "Generate a 100 random numbers\n"; 7963
srand( (unsigned)time( NULL ) );
cout.width(9); 1737
cout << rand() << endl; 31952
cout.width(9);
cout << rand() << endl; 17398
cout.width(9);
cout << rand() << endl;
cout.width(9);
cout << rand() << endl;
}
Code tested 07/22/2001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 212

Notes: 106
2006 C++ Course Handouts January 2006

Let’s See What We Know !!


Output…..
char x, y, z;
main(void) Enter a character:A
{ Enter a character:B
cout << "Enter a character:"; Enter a character:C
ABC
cin >> x;
198 Why?
cout << "Enter a character:"; 65
cin >> y;
cout << "Enter a character:";
cin >> z;
cout << x << y << z << endl;
cout << x + y + z << " Why?" << endl;
cout << (int) x << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 213

Artificial Intelligence

Reasoning ability
I drove the car into the garage and it died.

Woman, without her man, is lost


Woman, without her, man is lost

The committee denied the group a parade


permit because they feared violence.
The committee denied the group a parade
permit because they advocated violence.

How do we know who “they” are?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 214

Notes: 107
2006 C++ Course Handouts January 2006

Review
1. The value of a relational expression is zero if the expression is
__________________?
2. What does the following code fragment print?
score = 70;
cout << "Your Grade is " <<
(score < 60 ? "Fail“ : "Passing");
3. Discuss the break statement. Where is it used?
4. Discuss the continue statement. Where is it used?
5. What will the following code fragment print?
Counter = 10;
if (Counter = 11)
cout << “Counter equals 11” << endl;
6. Say we have the following expression and y=18, q=20, evaluate
the following expression:
((y<3) || (y>17) && q == 20)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 215

Homework
1. Should have read Chapters 1 through 4 by now
2. Read Chapter 5 for next week
3. Work on your term paper
4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 4 on page 249 of the text.
(Chapter 3)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 216

Notes: 108
2006 C++ Course Handouts January 2006

Chapter 4 Summary

Summary of Selection Structures

If Statement
If -- Else
Switch Statement
Logical Operators
Expressions
Goto Statement
Enumerated Types

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 217

Chapter 5

Looping in C++

While Loops
Do Loops
For…Next Loops
Continue Statement
Break Statement
Goto Statement
Test for Entrance Loop
Test for Exit Loop

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 218

Notes: 109
2006 C++ Course Handouts January 2006

While Loops

Basic Structure
while (expression)
C++ statement

Keeps looping while “expression” is TRUE !


Called an “Entry Condition” Loop
Also called a “Test For Entrance” Loop or “Pretest”
Loop
Why?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 219

While Loops

Single-statement body
while (Expression)
Single Statement;

Multi-statement body
while (Expression)
{
Statement-1;
Statement-2;
Statement-3;
Statement-n;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 220

Notes: 110
2006 C++ Course Handouts January 2006

While Loop Example 1


#include <iostream>
using namespace std;

void main()
{
int number;

while (number != 99)


{
cout << "Enter a number:";
cin >> number;
}
}

Verified
04/24/2003

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 221

While Loop Example 2


#include <iostream>
using namespace std;

Output
void main() Enter a Character:A
{ Count:1 A
char ch; Enter a Character:B
int x; Count:2 B
x = 1; Enter a Character:C
Count:3 C
while (ch != '$') Enter a Character:W
{ Count:4 W
cout << "Enter a Character:"; Enter a Character:X
cin >> ch; Count:5 X
cout << "Count:"; Enter a Character:#
cout << x++ << " "; Count:6 #
cout << ch << endl; Enter a Character:$
} Count:7 $
}

Verified
04/24/2003

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 222

Notes: 111
2006 C++ Course Handouts January 2006

While Loop Example 3


#include <iostream>
#include <iomanip>
using namespace std; Verified
10/24/2003
int main()
{
int days, count;
float total = 0.0; // Initialize accumulator

cout << "For how many days do you have sales figures? ";
cin >> days;

count = 1; // Initialize counter


while (count <= days)
{
float sales;
cout << "Enter the sales for day " << count << ": ";
cin >> sales;
total += sales; // Accumulate running total
count++; // Increment counter
}
cout << fixed << showpoint << setprecision(2);
cout << "The total sales are $" << total << endl;
return 0;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 223

An Entry Condition Loop

What happens in the following example ?

count = 10;
while (count <= 5)
{
cout << “Current Count:” << count++ << endl;
}

While is tested before execution

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 224

Notes: 112
2006 C++ Course Handouts January 2006

An Entry Condition Loop


What happens in the following example ?

count = 3;
while (count <= 5)
{
cout << “Current Count:” << count++ << endl;
}

While is tested before execution

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 225

Caution!

What happens in this example ?

count = 3;
while (count <= 5)
cout << “Current Count:” << count << endl;
count++;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 226

Notes: 113
2006 C++ Course Handouts January 2006

Caution!

What happens in this example ?

count = 3;
while (count = 5)
cout << “Current Count:” << count++ << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 227

Common Problems Using Loops


Common Problem (Not Incrementing Counter Variables)
x=0;
while (x<100)
cout << x;

Un-initialized counter variables


int count;
while (count>0)
{
Statement-1;
Statement-2;
}

Forgetting braces around multi-statement loops

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 228

Notes: 114
2006 C++ Course Handouts January 2006

Do While
Two Formats for the “Do While”
do {
statement-1;
statement-2;
statement-n;
} while (Boolean Expression);

do
statement-1;
while (Boolean Expression);

Keeps looping while “expression” is TRUE !


Called an “Exit Condition” Loop
Also called a “Test For Exit” Loop
Why?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 229

Do While

count = 0;
do
{
cout << “Current Count:” << count << endl;
count++;
}
while (count <= 5);

An Exit Condition Loop

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 230

Notes: 115
2006 C++ Course Handouts January 2006

Do While
#include <iostream>
using namespace std;

int main()
{
int score1, score2, score3;
float average;
char again;

do
{
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 231

Test for Entrance or Exit

Test for exit


count = 9;
do
cout << “Current Count:” << count++ << endl;
while (count < 5);

Test for entrance


count = 9;
while (count < 5)
cout << “Current Count:” << count++ << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 232

Notes: 116
2006 C++ Course Handouts January 2006

When to Use Do Loops


DO use do...while when you want to ensure the loop
is executed at least once. DO use while loops when
you want to skip the loop if the condition is false. DO
test all loops to make sure they do what you expect.

More Complicated while Statements


The condition tested by a while loop can be as
complex as any legal C++ expression. This can
include expressions produced using the logical &&
(AND), || (OR), and ! (NOT) operators

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 233

Determine the Min and Max on the Fly


double number_in, max, min;
int i=0;

Void main()
{
// Establish test variables
min=9999999.99;
max=0.0;

// Loop 7 times and prompt for numbers


// Test each number entered against test variables
// Set test variables to new maximum or minimum values
while (i < 8)
{
cout << i++ << ": Enter a floating point number:";
cin >> number_in;
if (number_in > max)
max = number_in;
if (number_in < min)
min = number_in;
}

// Print the results


cout << "Highest number entered is: " << max;
cout << " Lowest number entered is: " << min << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 234

Notes: 117
2006 C++ Course Handouts January 2006

The “For Loop”


General Syntax:
for (initialize; test; update action)
Other C++ statements

The loop is repeated until the test is false


Examples:

for (n=0; n<100; n++)


cout << n << “\n”;

for (n=100; n>10; n--)


cout << n << “\n”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 235

For Loop

Single-statement body
for (Initialization; Boolean Test; Update Action)
Single Statement;

Multi-statement body
for (Initialization; Boolean Test; Update Action)
{
Statement-1;
Statement-2;
Statement-3;
Statement-n;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 236

Notes: 118
2006 C++ Course Handouts January 2006

For Loop

Examples
for (count=0; count<1000; count++)
{
Statement-1;
Statement-2;
Statement-n;
}

for (int i=110; i<120; i=i+1)


{
Statement-1;
Statement-2;
Statement-n;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 237

For Loop

Examples
for (count=0; count<1000 && x>10; count++)
Statement-1;

for (int i=110; i<180; i=i+10)


{
Statement-1;
Statement-2;
Statement-n;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 238

Notes: 119
2006 C++ Course Handouts January 2006

For Loop

Common Problem
for (count=0; count<1000 && x>10; count++);
Statement-1;

for (int i=110; i<120; i=i+1);


{
Statement-1;
Statement-2; No Semi
} Colons Here

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 239

Multi-parameter for Loops


The for Statement
The syntax for the for statement is as follows:
for (initialization; test; action)
statement;

#include <iostream>
#include <iomanip>
using namespace std;
long x,y,z;

void main ()
{
for (x=0,y=0,z=0; x<10 && y<100 || z<50; x++, y=y+10, z=z+2)
{
cout << setw(8) << x << setw(8) << y << setw(8) << z << endl;
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 240

Notes: 120
2006 C++ Course Handouts January 2006

Null statements in for loops


#include <iostream>
using namespace std;

void main()
{
int counter = 0;

for( ; counter < 5; )


{
counter++;
cout << "Looping! ";
}

cout << "\nCounter: " << counter << ".\n";


}

output: Looping! Looping! Looping! Looping! Looping!


Counter: 5.

Verified
04/24/2003

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 241

Nested Loops Output


0 0
0 1
0 2
0 3
#include <iostream> 0 4
using namespace std; 1 0
1 1
int x, y; 1 2
1 3
main() 1 4
{ 2 0
for (y=0; y<5; y++) 2 1
for (x=0; x<5; x++) 2 2
cout << y << " " << x << endl; 2 3
} 2 4
3 0
3 1
3 2
3 3
3 4
4 0
4 1
4 2
Code Verified 6/21/2001 4 3
4 4

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 242

Notes: 121
2006 C++ Course Handouts January 2006

Nested Loops
#include <iostream>
using namespace std;

int x, y;

main()
{

for (y=0; y<5; y++)


{
for (x=0; x<5; x++)
{
cout << x << " " << y << endl;
}
} Same as previous example
but with braces showing
}
the nesting

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 243

continue statement
Code verified 6/21/01
Generated Output
Value of x is 3
Example of continue statement Value of x is 4
#include <iostream> Value of x is 5
using namespace std; Value of x is 6
Value of x is 7
int x;
Value of x is 8
int main(void) Value of x is 9
{ Value of x is 10
x = 0;
while (x < 20) Value of x is 11
{ Value of x is 12
x++;
if (x == 1 || x == 2) Value of x is 13
continue; Value of x is 14
cout << "Value of x is " << x << endl; Value of x is 15
} Value of x is 16
} Value of x is 17
Value of x is 18
Value of x is 19
Continue forces the Value of x is 20
next iteration of the
loop.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 244

Notes: 122
2006 C++ Course Handouts January 2006

Break Statement
Example
count = 100;
while (1)
{
if (count == 0)
break;
count--;
cout << count << endl;
}

While is always evaluated to true


Break used to “Get Out”
Count is is used then decremented

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 245

continue and break

continue and break


At times you'll want to return to the top of a while loop
before the entire set of statements in the while loop is
executed. The continue statement jumps back to the top
of the loop.
At other times, you may want to exit the loop before the
exit conditions are met. The break statement immediately
exits the while loop, and program execution resumes after
the closing brace.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 246

Notes: 123
2006 C++ Course Handouts January 2006

Loops are Great for Data Validation

int number;
do
{
cout << "Enter a number between 1 and 100: ";
cin >> number;

if (number < 1 || number > 100)


cout << "Invalid Number Entered! Try Again.\n\n";
}
while (number < 1 || number > 100);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 247

Loops in Review

1. What looping construct is used for a “Test for


Entrance” Loop?
2. What looping construct is used for a “Test for Exit”
loop?
3. The “for-loop” has _____ formal parameters?
4. What C++ statement can we use to get out of a
switch statement or a while loop?
5. What C++ statement can we use to force the next
iteration of a while loop?
6. While-loops, While-Loops, Do-while Loops and For
Loops all have a similar form factor. What is it?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 248

Notes: 124
2006 C++ Course Handouts January 2006

Homework
1. Should have read Chapters 1 through 5 by now
2. Read Chapter 6 for next week
3. Work on your term paper
4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 9 on page 310 of the text.
(Chapter 3)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 249

Chapter 5 Summary

Summary of Looping Structures

While loops
For loops
Do – While
Nested Loops
Test for Entrance
Test for Exit
Counters

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 250

Notes: 125
2006 C++ Course Handouts January 2006

Section 4b

Encryption Fundamentals

Brute Force attack


Caesar’s Cipher
XOR Cipher
Code Obfuscation
Vigenère Cipher
Random Mono-alphabet Cipher

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 251

Data Security Through Encryption


The process of scrambling data in a file so no one can interpret the
data unless they have a special software key

The Federal Data Encryption Standard (DES) used to be a good algorithm for
most commercial applications. But the Government never did trust the
DES to protect its own classified data, because the DES key length is only
56 bits, short enough for a brute force attack.

56 bit = 256-1 = 7.205757404x1016 or 72,057,574,040,000,000


64 bit = 256-1 = 1.844674407x1019 or 18,446,744,070,000,000,000
128 bit = 2128-1 = 3.402823669x1038 or …

DES 64-bit
Triple DES 128-bit
Rijndael 64-bit
RC2 64-bit

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 252

Notes: 126
2006 C++ Course Handouts January 2006

Data Security Through Encryption

What is a brute force attack?


Take the data in question and continue to
try different values for keys until you get
a meaningful result

Brute force method is used to crack Unix


passwords
Software called Satan

Take a copy of the Unix Password file


Use a dictionary of over a million words to
try each password

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 253

Basic Encryption (Caesar’s Cipher)


The process of scrambling data in a file
so no one can interpret the data unless
they have a special software key

Basic encryption is easy


Use a key from 1 to 25 and make an offset from
each letter.
Called the Caesar Cipher
Say, we choose 4 as the key
A becomes E, B becomes F, C becomes G, etc
All sorts of schemes for short runs of data
Say, we have a 10-byte product key
Add 1 to the 1st byte, 2 to the 2nd, 3 to the 3rd, and
so on

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 254

Notes: 127
2006 C++ Course Handouts January 2006

Basic Encryption (Caesar’s Cipher)


Key of 3
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
D E F G H I J K L M N O P Q R S T U V W X Y Z A B C

MEET ME AT MIDNIGHT becomes


PHHW PH DW PLGQLJKW

Easy to crack
Linguistic patterns are obvious
E is the most common letter, followed by t, a,
o, n
T is the most common letter to begin a word

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 255

Encryption – Random Mono-Alphabet


Random Mono-alphabet Cipher
Pick a word to use as the key, FEATHER, for example
Remove duplicate letters leaving, FEATHR
Use FEATHR to start then use remaining letters starting from
right to left

ABCDEFGHIJKLMNOPQRSTUVWXYZ
FEATHRZYXWVUSQPONMLKJIGDCB

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 256

Notes: 128
2006 C++ Course Handouts January 2006

Encryption -- Vigenère Cipher

Vigenère Cipher
Pick a word for the key, say TIGER
Use the ‘T’ as the starting offset

ABCDEFGHIJKLMNOPQRSTUVWXYZ
TUVWXYZABCDEFGHIJKLMNOPQRS

Then do it again using ‘I’ as the starting offset


ABCDEFGHIJKLMNOPQRSTUVWXYZ
IJKLMNOPQRSTUVWXYZABCDEFGH

Then again using G and then E and R


The word CAT becomes
VTM
DBU
And so on..

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 257

Basic Encryption (XOR Cipher)

Take each byte and XOR it with a number, say 6, for


example

A 65 01000001
XOR 06 00000110
G 72 01000111

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 258

Notes: 129
2006 C++ Course Handouts January 2006

Basic Encryption (XOR Cipher)

How do you do this with C++?

char ch=‘A’ Exclusive OR


char key=6;
char newchar;

newchar = ch ^ key;
cout << newchar;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 259

Basic Encryption (XOR Cipher)

How would you process an XOR


encrypted file without knowing
the specific key?

1. Open the message or file


2. Read each byte and XOR it with 1 and
display the message.
3. Loop from 1 through 255 and try each key.
4. Display the message using different key
values until you obtain a readable message

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 260

Notes: 130
2006 C++ Course Handouts January 2006

XOR Cipher Example

#include <iostream>
using namespace std;
void main(void)
{
const int MAX = 24;
char product_key[MAX] ="ABCD1234-2004";
char encrypted[MAX];
char decrypted[MAX];
int length, i, key=13;
Original Message:ABCD1234-2004
for (i=0; i<MAX; i++) Encrypted:LONI<?>9 ?==9
{
encrypted[i]='\0'; Decrypted:ABCD1234-2004
decrypted[i]='\0';
}

length = strlen(product_key);

for (i=0; i<length; i++)


encrypted[i] = product_key[i] ^ key;

cout << "Original Message:" << product_key << endl;


cout << " Encrypted:" << encrypted << endl << endl;

for (i=0; i<length; i++)


decrypted[i] = encrypted[i] ^ key;

cout << " Decrypted:" << decrypted << endl;


} Code Verified 09/28/2004

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 261

CERT Coordination Center

http://www.cert.org/advisories/
Carnegie Melon University Software Engineering
Institute
Several hundred per year are published
It is stated that 85% of the CERT advisories could have
been prevented by using cryptography
Black-box tests, White-box tests, Red Team Testing

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 262

Notes: 131
2006 C++ Course Handouts January 2006

Encryption Summary

Summary of Encryption

Brute Force attack


Caesar’s Cipher
XOR Cipher
Code Obfuscation
Vigenère Cipher
Random Mono-alphabet
Cipher

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 263

Chapter 6

Functions

Top Down Design


Predefined Functions
User-Defined Functions
Black Box Analogy
Scope
Call by Value
Call by Reference
Function Overloading

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 264

Notes: 132
2006 C++ Course Handouts January 2006

Functions
What is a function?
1. Who can explain what a function is in terms of
mathematics?
2. What is reusable code?
3. Why do we create and use software functions?
4. Who can describe the difference between
programmer defined and built-in functions?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 265

Functions

What is a function?

A function is a self-contained unit of


program code designed to accomplish a
particular task.
Also known as subroutines or procedures
in other languages.
Saves you from repetitious programming.
Black Box Concept.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 266

Notes: 133
2006 C++ Course Handouts January 2006

Black Box Effect of Functions

Black Box Effect


Thevenin’s Theorem in Engineering

Pass in Some Data Function Return A Result

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 267

Analogous to a Mathematics Function

y = mx + b
Where
¾ y is the return value
¾ m, x and b are passed arguments
Arguments can be numeric, character, etc
Return values can be numeric or character

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 268

Notes: 134
2006 C++ Course Handouts January 2006

Functions - Syntax

Function Definition:
return_type function_name (arg1_type arg-1, arg2_type
arg-2, arg-n..)
{
C++ statements
.
.
return(value);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 269

Functions – 3 Parts
The Prototype:
return_type function_name(arguments);

Function Call:
receiving_variable =
function_name(arguments);

Function Definition:
return_type function_name(arguments)
{
C++ statements;
return(value);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 270

Notes: 135
2006 C++ Course Handouts January 2006

Functions - Syntax
Example showing integer return value
int result;
Prototype:
int squared(int x);

Calling a Function:
result = squared(10);

Function:
int squared(int x)
{
x=x*x;
return(x);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 271

Declaring a Function

There are three ways to declare a


function:
1. Write your prototype into a file, and then
use the #include directive to include it in
your program.
2. Write the prototype into the file in which
your function is used.
3. Define the function before it is called by any
other function. When you do this, the
definition acts as its own declaration.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 272

Notes: 136
2006 C++ Course Handouts January 2006

Prototype Variations
Prototype Variations
int squared(int x);
float cubed(float z);
char status(char ch);
void display(int x, int y, int z);
void printone(char c, int x, float q);
void swap(long x, long y);
bool thing(void);
double test_for_whatever(int, float, bool);

Compiler looks for the number of arguments and the argument


type.
A prototype defines to the compiler the functions of a given
program, its arguments and its return data type

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 273

Functions - No Arguments

Returns Nothing
#include <iostream>
using namespace std;
void put_asterisk(void);
Passed Nothing
int i;
int main()
{
put_asterisk();
put_asterisk();
put_asterisk(); Note
return(0);
}
void put_asterisk()
{
cout << “*”;
}
Note: void means no argument expected

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 274

Notes: 137
2006 C++ Course Handouts January 2006

Functions - Global Variables


// code verified 10/31/2002
#include <iostream>
using namespace std;
void put_asterisk(char ch); // prototype
int i;
char ch4='!';

void main()
{
char ch1='*';
char ch2='$';
char ch3='A';

put_asterisk(ch1); // function call


put_asterisk(ch2); Generated Output
put_asterisk(ch3); *!
} $!
A!
// Function to print the character that is passed
void put_asterisk(char ch) // definition
{
cout << ch << ch4 << endl; Code Verified 5/31/2001
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 275

Functions - Return Values


// code verified 10/31/2002
include <iostream>
using namespace std;
float num1, num2, ans;
float calc(float a, float b); // Function prototype
Generated Output
void main(void)
The passed values are:
{
num1=12.1;
12.1 9.9
num2=9.9; The returned value is:
ans=calc(num1, num2); 0.0183655
cout << "The returned value is: " << ans <<endl;
}

// Define the actual function


float calc(float num1, float num2)
{
float answer;
cout << "The passed values are: " << num1 << " " << num2 <<
endl;
answer = (num1-num2)/(num1*num2);
return(answer);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 276

Notes: 138
2006 C++ Course Handouts January 2006

Functions - Return Values


#include <iostream>
#include <iomanip>
using namespace std;

float getRadius();
float square(float);

void main()
{
const float pi = 3.14159;
float rad;

cout << fixed << showpoint << setprecision(2);


cout << "This program calculates the area of a circle.\n";
rad = getRadius();
cout << "The area is " << pi * square(rad) << endl;
}

float getRadius()
{
float radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
return radius;
}

float square(float number)


{
return number * number;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 277

Pre-defined Functions

int x=25;
float y=3.2;

sqrt(x) returns 5
pow(2, 5) returns 32
abs(-9) returns 9
labs(-90000) returns 90000
fabs(-7.56) returns 7.56
ceil(y) returns 4.0 rounded up
ceil(3.9) returns 4.0 rounded up
floor(y) returns 3.0 rounded down
floor(3.9) returns 3.0 rounded down

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 278

Notes: 139
2006 C++ Course Handouts January 2006

C++ Is Very Function Oriented

Examples of Function Calls:


display_totals();
display_totals(amt1, amt2);
x = compute_total(amt1, amt2);
fopen(filename,”r”);
status=fopen(filename,”r”);
printf(“This is C++ at its Finest.“);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 279

Using Functions as Parameters to Functions

Although it is legal for one function to take as a parameter a second


function that returns a value, it can make for code that is hard to
read and hard to debug.
As an example, say you have the functions double(), triple(),
square(), and cube(), each of which returns a value. You could
write

Answer = (double_it(triple(square(cube(myValue)))));

This statement takes a variable, myValue, and passes it as an


argument to the function cube(), whose return value is passed as
an argument to the function square(), whose return value is in
turn passed to triple(), and that return value is passed to
double(). The return value of this doubled, tripled, squared, and
cubed number is now passed to Answer.
It is difficult to be certain what this code does (was the value tripled
before or after it was squared?), and if the answer is wrong it will
be hard to figure out which function failed.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 280

Notes: 140
2006 C++ Course Handouts January 2006

System Function v. Programmer Defined


// code verified 10/31/2002
#include <iostream>
using namespace std; Return and main are
int y = 60;
int displaytext(void); system functions
void main(void)
{
int x = 100;
cout << "Displaytext Returns " << displaytext();
cout << endl;
}
Output
// Programmer defined function x=90 y=60
displaytext() Displaytext
{ Returns 90
int x = 90;
cout << "x=" << x << " y=" << y << endl;
return(x);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 281

Default Arguments
#include <iostream>
using namespace std;

void displayStars(int = 10, int = 1);

void main()
{
displayStars(); // Uses default values cols and rows
cout << endl;
displayStars(5); // Uses 5 for cols and default value for rows
cout << endl;
displayStars(7, 3); // Uses 7 for cols and 3 for rows
}

void displayStars(int cols, int rows)


{
for (int down = 0; down < rows; down++)
{
for (int across = 0; across < cols; across++)
cout << '*';
cout << endl;
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 282

Notes: 141
2006 C++ Course Handouts January 2006

Graphical Representation
Windows

or
Main()
DOS
Function A
Function D

Function B Function C

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 283

Variable Scope
// code verified 10/31/2002
#include <iostream>
int y = 60; // Global Variable
int displaytext(int abc); // prototype scope
void main(void)
{
int x = 10; // Local to the main
cout << "Displaytext Returns " << displaytext(x);
cout << endl;
}

// Programmer defined function


displaytext(int abc)
{
int x = 90; // local to the function
cout << "x=" << x << " y=" << y << " abc=" << abc << endl;
return(x);
}

Generated Output
x=90 y=60 abc=10
Displaytext Returns 90

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 284

Notes: 142
2006 C++ Course Handouts January 2006

Variable Scope

File Scope Global


Function Scope Local to function
Block Scope Local to surrounding block
Prototype Scope Local to prototype only

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 285

Local and Global Variables


Local Variables
Not only can you pass in variables to the function, but you also can
declare variables within the body of the function. This is done
using local variables, so named because they exist only locally
within the function itself. When the function returns, the local
variables are no longer available.
Local variables are defined like any other variables. The parameters
passed in to the function are also considered local variables and
can be used exactly as if they had been defined within the body
of the function.

Global Variables
Variables defined outside of any function have global scope and
thus are available from any function in the program, including
main().
Local variables with the same name as global variables do not
change the global variables. A local variable with the same name
as a global variable hides the global variable, however. If a
function has a variable with the same name as a global variable,
the name refers to the local variable--not the global--when used
within the function.
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 286

Notes: 143
2006 C++ Course Handouts January 2006

Variable Scope
#include <iostream>
int cube_it(int x); // prototype scope

int i=100; // global scope

// passed argv from DOS command line


// passed environment variables in envp
int main(int argc, char *argv[], char *envp[])
{
int cost_of_goods_sold=0.0; // local to the main
int i=0;
{
int i=10; // local to block
cout << cube_it(i) << endl;
return(0);
}
}

int cube_it(int c)
{
int cubed_value=0; // local to the function
cubed_value=c*c*c;
return(cubed_value);
Code Verified 10/31/2001
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 287

The Return Statement

#include <iostream>
using namespace std; Code Verified 5/31/2001

double cube_it(double x);

int main(void)
{
double cube;
cube = cube_it(10.0);
cout << cube << endl << endl;
return(0);
}

double cube_it(double c)
{
double cubed_value=0.0;
cubed_value=c*c*c;
return(cubed_value);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 288

Notes: 144
2006 C++ Course Handouts January 2006

Return Values

Several forms of return statements

return 5; // returns 5
return (5); // returns 5
return (x > 5); // returns true if x > 5
return (MyFunction()); // calls MyFunction
return; // simply bails out

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 289

Return Statement in a Void Function

void print_headings(long kwh)


{
cout << "Monthly Usage Report " << endl;
cout << "-------------------------" << endl;
cout << "Customer KWH " << endl;
if (kwh == 0.0)
return;
else
cout << customer_name << " " << kwh << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 290

Notes: 145
2006 C++ Course Handouts January 2006

Automatic Local Variables (Default)

Each call to a function creates a new copy of


all the variables declared in the function.
This is automatic and can be stated so on
the declarations with the auto keyword

void showVariable()
{
auto int myNum=0; // default
cout << "StatNum is " << myNum << endl;
myNum++;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 291

Automatic Local Variables (Default)


#include <iostream> Generated Output:
using namespace std; StatNum is 0
void showVariable(); StatNum is 0
StatNum is 0
int main() StatNum is 0
{ StatNum is 0
for (int count = 0; count < 9; count++) StatNum is 0
showVariable();
return 0; StatNum is 0
} StatNum is 0
StatNum is 0

void showVariable()
{
int myNum=0;
cout << "StatNum is " << myNum << endl;
myNum++;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 292

Notes: 146
2006 C++ Course Handouts January 2006

Static Local Variables


#include <iostream> Generated Output:
using namespace std; StatNum is 0
void showVariable(); StatNum is 1
StatNum is 2
int main() StatNum is 3
{ StatNum is 4
for (int count = 0; count < 9; count++) StatNum is 5
showVariable();
return 0; StatNum is 6
} StatNum is 7
StatNum is 8

void showVariable()
{
static int myNum=0;
cout << "StatNum is " << myNum << endl;
myNum++;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 293

Break

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 294

Notes: 147
2006 C++ Course Handouts January 2006

Call by Value
// code verified 10/31/2002
int a,b;
void swap(int x, int y);

void main(void) Output


{
a=100; A=100
b=200;
cout << "a=" << a << endl;
B=200
cout << "b=" << b << endl; A=100
swap(a, b);
cout << "a=" << a << endl; B=200
cout << "b=" << b << endl;
}

void swap(int x, int y)


{ Arguments
int hold;
hold=x; NOT Affected
x=y;
y=hold;
}

Generated Output
a=100
b=200
a=100
b=200

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 295

Call By Reference Example


// Example of Call by Reference Functions Code verified 6/26/2001
#include <iostream>
using namespace std;
void get_input(int& n1, int& n2); // Prototype parameters
void main(void)
{
int first_num, second_num;
get_input(first_num, second_num);
cout << "Number One Entered:" << first_num << endl;
cout << "Number Two Entered:" << second_num << endl;
}

// Get user input


// prompt user for 2 integers
// Pass values back through passed arguments
void get_input(int& num1, int& num2)
{
cout << "Enter Number 1:"; Actual values of first_num and
cin >> num1;
cout << "Enter Number 2:"; second_num are modified within
cin >> num2; the function and the arguments
} themselves are modified.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 296

Notes: 148
2006 C++ Course Handouts January 2006

Call By Value Example


// Example of Call by Value Functions Code verified 6/26/2001
#include <iostream>
using namespace std;
void get_input(int n1, int n2); // Prototype, formal parameters
void main(void)
{
int first_num, second_num;
get_input(first_num, second_num);
cout << "Number One Entered:" << first_num << endl;
cout << "Number Two Entered:" << second_num << endl;
}

// Get user input


// Prompt user for 2 integers
// Attempt to pass values back through passed arguments
void get_input(int num1, int num2)
{ Call by Value is the default
cout << "Enter Number 1:"; function calling method which
cin >> num1;
cout << "Enter Number 2:"; does NOT modify the
cin >> num2; arguments. Data is protected.
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 297

Swap Example
void get_input(int& n1, int& n2); // Prototype, formal parameters
void swap(int& n1, int& n2);
void main(void) Code verified 6/26/2001
{
int first_num, second_num;
get_input(first_num, second_num);
swap(first_num, second_num);
cout << "Number One Entered:" << first_num << endl;
cout << "Number Two Entered:" << second_num << endl;
}

// Get user input


// prompt user for 2 integers
// Pass values back through passed arguments
void get_input(int& num1, int& num2)
{
cout << "Enter Number One:";
cin >> num1;
cout << "Enter Number Two:";
cin >> num2;
}

// Swap the values that are passed


// Pass values back through passed arguments
void swap(int& num1, int& num2)
{
int temp;
temp = num1;
num1 = num2;
num2 = temp;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 298

Notes: 149
2006 C++ Course Handouts January 2006

Simulate a Roll of a Die (1 of 2)


#include <iostream> // has cout stuff Simulate 30 rolls of a die
#include <stdlib.h> // Has srand function Seed is 10991041372
#include <time.h> // has time functions 1
#include <iomanip> // for setw 1
4
using namespace std; 6
const int MAX=1000000; 4
3
unsigned x, seed; 5
int roll; 5
double percent; 4
unsigned arr[6]; 6
5
void main( void ) 6
2
{
2
// Housekeeping, initialize arrays, etc 6
for (x=0; x<6; x++) 5
arr[x]=0; 5
1
cout << "Simulate 10 rolls of a die\n"; 4
seed = (unsigned)time( NULL ); 1
cout << "Seed is " << seed; 1
1
// First, print out 30 die throws 1
srand(seed); 2
for(x = 0; x<30; x++ ) 2
{ 2
roll = rand() % 6 + 1; 2 Code tested 10/22/2004
cout << roll << endl; 6
3
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 299

Simulate a roll of a die (2 of 2)


// Next simulate 1 million throws and check the distribution
srand(seed);
for(x = 0; x<MAX; x++ )
{
roll = rand() % 6;
arr[roll]++;
}
// Calculate and display distribution and percentages
cout << "Die Count Percent\n";
for (x=0; x<6; x++)
{
percent = ((double) arr[x] / (double) MAX) * 100.00;
cout << setw(2) << x+1 << setw(9)
<< arr[x] << setprecision(4)
<< setw(9) << percent << endl;
}
} Die Count Percent
1 166191 16.62
2 167280 16.73
3 166278 16.63
4 166102 16.61
5 167434 16.74
6 166715 16.67

Code tested 10/22/2004

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 300

Notes: 150
2006 C++ Course Handouts January 2006

Function Overloading
Functions with the same name but with different argument
lists
Example: Say we want to square a number, but want to
pass it different types of variables. (long, int, float,
double, for instance)

In Standard C and C++, the function prototypes look like:


int square_int(int);
long square_long(long);
float square_float(float);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 301

Function Overloading
// code verified 10/31/2002
#include <iostream>
using namespace std;

int cube(int);
float cube(float);

int int_input;
float flt_input;

void main(void)
{
cout << "Enter an integer to cube:";
cin >> int_input;
cout << "Enter a float to cube:";
cin >> flt_input;
cout << int_input << " cubed is " << cube(int_input) << endl;
cout << flt_input << " cubed is " << cube(flt_input) << endl;
}

int cube(int n) {
return(n*n*n);
}

float cube(float n) {
return(n*n*n);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 302

Notes: 151
2006 C++ Course Handouts January 2006

Function Overloading (Polymorphism)


#include <iostream>
using namespace std;
long vector;
int counter;
float standard_deviation;
double mass_of_the_sun;
Called
// Function Prototypes
int square(int); Polymorphism
long square(long);
float square(float);
double square(double;

Note same function


int main(void) name but different
{
square(counter);
argument types
square(standard_deviation);
square(vector);
square(mass_of_the_sun);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 303

Function Overloading
int square(int q) {
return(q*q);
}

float square(float q) { Note here, in C++, the


return(q*q); function names are all the
}
same. Only the return types
and argument lists are
long square(long q) {
return(q*q);} different.

double square(double q) {
return(q*q);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 304

Notes: 152
2006 C++ Course Handouts January 2006

Function Overloading
int mean(int n1, int n2, int n3);
int mean(int n1, int n2, int n3, int n4);

int main(void)
{
m = mean(2, 4, 6);
m = mean(100, 120, 233, 444);
return(0);
}

int mean(int n1, int n2, int n3) {


return((n1 + n2 + n3)/3);
}

int mean(int n1, int n2, int n3, int n4) {


return((n1 + n2 + n3 + n4)/4);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 305

Function Overloading
bool deposit(double amt, string acct);
bool deposit(string date, double amt, string acct);

int main(void)
{
deposit(date, amount, account);
deposit(amount, account);
}

bool deposit(string date, double amt, string acct) {


return(true);
}

bool deposit(double amt, string acct) {


date = todays_date;
return(true);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 306

Notes: 153
2006 C++ Course Handouts January 2006

Function Templates, Embedded


#include <iostream>
using namespace std; Code Tested 10/03/2004
// Get input data template
template <class T1>
T1 square(T1 number)
{
return(number * number);
}
void main(void)
{
int num0=10;
short num1=10;
long num2=10L;
double num3=10.21;
float num4=10.21F;
cout << num0 << " Squared is " << square(num0) << endl;
cout << num1 << " Squared is " << square(num1) << endl;
cout << num2 << " Squared is " << square(num2) << endl;
cout << num3 << " Squared is " << square(num3) << endl;
cout << num4 << " Squared is " << square(num4) << endl;
cout << "10 Squared is " << square(10) << endl;
cout << "10.21 Squared is " << square(10.21) << endl;
cout << "10.21F Squared is " << square(10.21F) << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 307

Function Templates, Header Files


#include <iostream>
using namespace std; Code Tested 10/03/2004

#include <c:/progs/square_template.h> // squared template


// Get input data template
// Main Logic Area template <class T1>
void main(void) T1 square(T1 number)
{
int num0=10; {
short num1=10; T1 result;
long num2=10L; result = number * number;
double num3=10.21; return(result);
float num4=10.21F;
}

cout << num0 << " Squared is " << square(num0) << endl;
cout << num1 << " Squared is " << square(num1) << endl;
cout << num2 << " Squared is " << square(num2) << endl;
cout << num3 << " Squared is " << square(num3) << endl;
cout << num4 << " Squared is " << square(num4) << endl;
cout << "10 Squared is " << square(10) << endl;
cout << "10.21 Squared is " << square(10.21) << endl;
cout << "10.21F Squared is " << square(10.21F) << endl;
cout << "Completed...\n\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 308

Notes: 154
2006 C++ Course Handouts January 2006

Function Templates, Header Files


#include <iostream>
#include <iomanip> Code Tested 10/03/2004
using namespace std;

#include <c:/progs/Swap_template.h> // squared template


//Get input data template
template <class T1>
void square(T1 &x, T1 &y)
{
T1 temp;
// Main Logic Area temp = x;
void main(void) x = y;
{ y = temp;
int num1=1000; }
int num2=2000;
cout << setw(12) << num1 << setw(12) << num2 << endl;
swap(num1, num2);
cout << setw(12) << num1 << setw(12) << num2 << endl;

cout << "Test Completed...\n\n";


}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 309

Function Templates, System Supplied


#include <iostream> Code Tested 10/03/2004
#include <iomanip>
#include <algorithm> // system supplied swap template
using namespace std;

// Main Logic Area


void main(void)
{
int num1=1000;
int num2=2000;
cout << setw(12) << num1 << setw(12) << num2 << endl;
swap(num1, num2);
cout << setw(12) << num1 << setw(12) << num2 << endl;

cout << "Test Completed...\n\n";


}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 310

Notes: 155
2006 C++ Course Handouts January 2006

Quick Review of Functions


#include <iostream>
using namespace std;
int cube_it(int x);

int main(void)
{
int x = 10;
cout << “Initial:” << x << endl;

cube_it(x);
int cube_it(int x)
return(0); {
} int value;
value= x * x * x;
cout << value;
return(value);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 311

Review Questions
1. What are the three main pieces you need to consider when
designing and using a function?
2. What type of arguments can be passed to a C++ function?
3. Is there a particular order to the arguments passed to a
function?
4. What is the scope of a global variable?
5. The ceil() function is known as what type of C++ function?
6. The “return” function, when used without an argument, is used
to __________?
7. Which “Call by” method can be used to modify a function’s
arguments?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 312

Notes: 156
2006 C++ Course Handouts January 2006

Homework
1. Should have read Chapters 1 through 6 by now
2. Read Chapter 7 for next week
3. Work on your term paper

4. Classroom Group Activity: Break into groups of 2, 3 or


4 students. Do problem 2 on page 386 of the text.
(Chapter 6)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 313

Chapter 6 Summary

C++ Functions
Built-in Functions
User Defined Functions
Definitions
Prototypes
Calling by Reference
Calling by Value
Overloading

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 314

Notes: 157
2006 C++ Course Handouts January 2006

Chapter 7
Data Structures and Classes
¾ Classes
¾ Encapsulation
¾ Constructors
¾ Struct Type

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 315

Data Structures

We have already studied: char, long, double, float


data types. These are system defined data
types.

Now we are going to add user defined data types,


called abstract data types. This is where we
bring together the primitive data types into data
types of our own design.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 316

Notes: 158
2006 C++ Course Handouts January 2006

Data Structures

struct CDAccount // Structure Tag or Template


{
double balance; // Member Names
double interest_rate;
int term;
};

struct CDAccount { // Structure Tag or Template


double balance; // Member Names
double interest_rate;
int term; };

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 317

Data Structures
struct CDAccount // Structure Tag or Template
{
double balance; // Member Names
double interest_rate;
int term; Define the data type
};

int main(void) Define the variable


{
CDAccount my_account, your_account; // Structure Variables
float cost_of_goods_sold;
}

Code verified 11/04/01

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 318

Notes: 159
2006 C++ Course Handouts January 2006

Data Structures

struct Time // Structure Tag or Template


{
int hour;
int minute;
int seconds;
};

int main(void)
{
Time now; // structure variable
}

Code verified 11/04/01

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 319

Data Structures
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
struct Circle // Structure Tag or Template
{
double radius;
double diameter;
double area;
};
const double pi=3.14159;
void main(void)
{
Circle c; // structure variable
// Get user input
cout << "Enter the diameter:";
cin >> c.diameter;
// Do calculations
c.radius = c.diameter / 2;
c.area = pi * pow(c.radius, 2.0);
// Do Output
cout << fixed << showpoint << setprecision(2);
cout << "Radius: " << setw(6) << c.radius << endl;
cout << " Area: " << setw(6) << c.area << endl;
}
Code verified 04/14/03

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 320

Notes: 160
2006 C++ Course Handouts January 2006

DOT Operator
Syntax:
Structure_Variable_Name.Member_Variable_Name
Example:
struct StudentRecord
{
int student_number;
int student_age;
char student_grade;
};

int main(void)
{
StudentRecord your_record;
your_record.student_number = 20082;
your_record.student_grade = ‘A’; Code verified 11/04/01
your_record.student_age=32;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 321

Initializing a Structure
struct StudentRecord
{
int student_number;
int student_age;
char student_grade;
};

int main(void)
{
StudentRecord your_record={12345, 32, ‘A’};
// or
your_record.student_number=12345;
your_record.student_age=32;
your_record.student_grade=‘A’;
}
Code verified 11/04/01

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 322

Notes: 161
2006 C++ Course Handouts January 2006

Data Structures
#include <iostream>
using namespace std;

struct book { // Structure Template


char title[30];
char author[25];
int quantity;
float cost;
};

void main(void)
{
book library; // Structure Variable
cout << " Enter Book Title:";
cin >> library.title;
cout << "Enter Authors Name:";
cin >> library.author;
cout << " Enter Recent Cost:";
cin >> library.cost;

cout << library.title << " ";


cout << library.author << " ";
cout << library.cost << endl; Code verified 11/04/01
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 323

Alternate Way of Declaring Structure Variables

struct book
{ // Structure Template
char title[30];
char author[25];
int quantity;
float cost;
} library; // Structure Variable

Code verified 11/04/01

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 324

Notes: 162
2006 C++ Course Handouts January 2006

Passing Structure Members to Functions


#include <iostream>
using namespace std;
struct book
{ // Structure Template
char title[30];
char author[25];
int quantity;
float cost;
} library; // Structure Variable
float invcost(int, float);
int main(void)
{
cout << "Enter Book Quantity:";
cin >> library.quantity;
cout << "Enter Book Cost:";
cin >> library.cost;
cout << invcost(library.quantity, library.cost) << endl;
return(0);
}

// Function to compute inventory cost


float invcost(int quan, float cost)
{
return(quan * cost);
}
Validated 7/13/2001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 325

Passing Structure Members to Functions

#include <iostream>
using namespace std;
struct book
{ // Structure Template
char title[30];
char author[25];
int quantity;
float cost;
} library; // Structure Variable
// Prototypes
float calculate(float, int);
void get_input(float&, int&);
int main(void)
{
get_input(library.cost, library.quantity);
cout << calculate(library.cost, library.quantity) << endl;
return(0);
}

float calculate(float cost, int quan)


{
return(quan * cost);
}

void get_input(float& c, int& q)


{
cout << "Enter Book Quantity:";
cin >> q;
cout << "Enter Book Cost:";
cin >> c; Validated 7/13/2001
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 326

Notes: 163
2006 C++ Course Handouts January 2006

Returning a Structure From a Function (1 of 2)


struct Circle
{
float radius;
float diameter; Validated 11/22/2003
float area;
};
Circle getInfo();
const double pi = 3.14159;
void main()
{
Circle c1, c2;
c1 = getInfo();
c2 = getInfo();
1 of 2
c1.area = pi * pow(c1.radius, 2.0);
c2.area = pi * pow(c2.radius, 2.0);
cout << fixed << showpoint << setprecision(2);
cout << "\nThe radius and area of the circles are\n";
cout << "Circle 1 -- Radius: " << setw(6) << c1.radius
<< " Area: " << setw(6) << c1.area << endl;
cout << "Circle 2 -- Radius: " << setw(6) << c2.radius
<< " Area: " << setw(6) << c2.area << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 327

Returning a Structure From a Function (2 of 2)

Circle getInfo()
{ Validated 11/22/2003
Circle round;
cout << "Enter the diameter of a circle: ";
cin >> round.diameter;
round.radius = round.diameter / 2;
return round;
}

Enter the diameter of a circle: 32


Enter the diameter of a circle: 43

The radius and area of the circles are


Circle 1 -- Radius: 16.00 Area: 804.25
Circle 2 -- Radius: 21.50 Area: 1452.20

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 328

Notes: 164
2006 C++ Course Handouts January 2006

Nested Structures
struct ChkDate
{ Validated 11/04/2001
int year;
int month;
int day;
}; // Structure Variable

struct book
{ // Structure Template
char title[30];
char author[25];
int quantity;
float cost;
ChkDate check_out;
}; // Structure Variable

book library;
ChkDate date;

int main(void)
{
ChkDate newdate = {2000, 02, 22}; // initializing
cout << library.check_out.day;
cout << date.year << endl;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 329

Nested Structures
struct AnnualCostInfo
{
float food, medical, license, misc;
}; Validated 11/22/2003

struct PetInfo
{
string name; Annual costs for my 5-year-old cat Sassy are $457.00
string type;
int age;
AnnualCostInfo cost;
};

void main()
{
PetInfo pet; // Define a structure variable

pet.name = "Sassy";
pet.type = "cat";
pet.age = 5;
pet.cost.food = 250.00;
pet.cost.medical = 150.00;
pet.cost.license = 7.00;
pet.cost.misc = 50.00;

cout << fixed << showpoint << setprecision(2);


cout << "Annual costs for my " << pet.age << "-year-old " << pet.type << " "
<< pet.name << " are $"
<< (pet.cost.food + pet.cost.medical + pet.cost.license +
pet.cost.misc) << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 330

Notes: 165
2006 C++ Course Handouts January 2006

Structure Constructors
struct Employee
{
int employees; Validated 11/22/2003
int year;
float payrate;
Employee() Employees: 120
{ Fiscal Year: 2004
employees =120;
year =2004; Starting Rate: 25.55
payrate =25.55;
}
};

void main(void)
{
Employee emp;
cout << " Employees: “ << emp.employees << endl;
cout << " Fiscal Year: “ << emp.year << endl;
cout << "Starting Rate: “ << emp.payrate << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 331

Structure Constructors
#include <iostream.h>
struct Employee
{ Validated 11/22/2003
int employees;
int year;
float payrate;

Employee(int e, int y, float p)


{
employees =e;
year =y; Structure constructors
payrate =p; accept arguments, too
}
};

void main(void)
{
Employee emp(120, 2004, 25.55);
cout << " Employees: “ << emp.employees << endl;
cout << " Fiscal Year: “ << emp.year << endl;
cout << "Starting Rate: “ << emp.payrate << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 332

Notes: 166
2006 C++ Course Handouts January 2006

Structures as Bit Fields


Structures can be used to identify individual bit
fields
struct {
unsigned field1 : 1;
unsigned field2 : 1;
unsigned field3 : 1;
unsigned field4 : 1;
} fourbits;

struct {
unsigned field1 : 1; // max value is 1
unsigned field2 : 1;
unsigned field3 : 3; // max value is 7
unsigned field4 : 3;
} mybits;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 333

Structures as Bit Fields

struct {
unsigned first : 1;
: 2;
unsigned second : 1;
: 3;
unsigned third : 2;
} gaps;

Max Values for some bit fields


Bits Maximum Value
1 1
2 3
3 7
4 15
5 31
6 63

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 334

Notes: 167
2006 C++ Course Handouts January 2006

Structures as Bit Fields


PC Configuration switches
struct equip_word {
unsigned has_drive : 1;
unsigned : 1;
unsigned mother_bd : 2;
unsigned video_card : 2;
unsigned num_drives : 2;
unsigned : 1;
unsigned com_cards : 3;
unsigned game_port : 1;
unsigned : 1;
unsigned printers : 2; };

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 335

Unions (1 of 2)

Unions variables share the


#include <iostream> same memory space
#include <iomanip>
using namespace std;

union PaySource // Declare a union.


{
short hours; // These two variables share
float sales; // the same memory space.
};

1 of 2

Validated 11/22/2003

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 336

Notes: 168
2006 C++ Course Handouts January 2006

Unions (2 of 2)
void main()
{
PaySource employee1; // employee1 is a PaySource union.

char hourlyType; // 'y' if hourly, 'n' if on commission


float payRate, grossPay;

cout << fixed << showpoint << setprecision(2);


cout << "This program calculates either hourly wages or sales commission.\n";
cout << "Is this an hourly employee (y or n)? ";
cin >> hourlyType;

if (hourlyType == 'y') // This is an hourly employee.


{
cout << "What is the hourly pay rate? ";
cin >> payRate; Shares the same
cout << "How many hours were worked? ";
cin >> employee1.hours; memory space
grossPay = employee1.hours * payRate;
cout << "Gross pay: $" << grossPay << endl;
}
else // Employee works on commission.
{
cout << "What are the total sales for this employee? ";
cin >> employee1.sales;
grossPay = employee1.sales * 0.10;
cout << "Gross pay: $" << grossPay << endl; Validated 11/22/2003
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 337

Encapsulation & Data Hiding

When you add a resistor to an existing circuit, you


pick a pre-manufactured component.
When you build a new garage, you use pre-
configured lumber. (2x4, 2x8, etc)
When you add a function to a C++ program you use
pre-existing functions.
The Property of a self-contained program unit is
called encapsulation.
Using the encapsulated unit without regard to how it
works is referred to as data hiding

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 338

Notes: 169
2006 C++ Course Handouts January 2006

Inheritance & Reuse

When engineers build a new car they reuse many


components
They modify an existing model
In C++ a new data type can be declared which is
an extension of an existing data type
This done through the use of inheritance

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 339

Classes
Classes hold member functions as well as variables
Syntax
class class_name
{
public:
member specification-1
member specification-2
member specification-3
member specification-n
private:
member specification-n+1
member specification-n+2
member specification-n+3
member specification-n+4
};

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 340

Notes: 170
2006 C++ Course Handouts January 2006

Classes
Classes hold member functions as well as variables
class class_name
{
public:
member specification-1
Once a class is defined, an
member specification-2 object is created. An object
member specification-3
member specification-n is similar to a variable of
private:
member specification-n+1
the class type
member specification-n+2
member specification-n+3
member specification-n+4
};

int main(void)
{
class_name object_name;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 341

Classes
Classes hold member functions as well as variables
#include <iostream>
using namespace std; Code verified 11/04/2001
class DayOfYear
{
public: // Public members
void output(); // member function prototype
int month;
int day;
int year;
private:
float cost;
};
DayOfYear today, birthday; // Declare abstract variables
int main(void)
{ Scope Resolution Operator
cin >> today.month;
cin >> today.day;
cin >> today.year;
today.output();
}

void DayOfYear::output() // Member Function


{
cout << month << "/" << day << "/" << year << cost << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 342

Notes: 171
2006 C++ Course Handouts January 2006

Classes
#include <iostream>
using namespace std;
class DayOfYear
{
public: // Public members Code verified 11/06/2001
void output(); // member function prototype
int month; // variables
int day;
int year;
private:
float cost; // Can only be used in member functions
};
DayOfYear today, birthday; // Declare abstract variables
void main(void)
{
cin >> today.month;
cin >> today.day;
cin >> today.year;
// cin >> cost; // Error since cost is private
cin >> birthday.month;
cin >> birthday.day;
cin >> birthday.year; Classes hold member
today.output();
birthday.output(); functions as well as
} variables
void DayOfYear::output() // Member Function
{
cout << month << "/" << day << "/" << year << endl;
cout << cost << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 343

Classes
class DayOfYear
{
Private Members
public:
void output(); // member function prototype
void get_dates(); // member function prototype
int month;
int day; Code verified 11/06/2001
int year;
private:
int birth_year;
};
DayOfYear today, birthday; // Declare abstract variables
void main(void)
{
today.get_dates(); // Load today
today.output(); // Dump today
birthday.get_dates(); // Load birthday
birthday.output(); // Dump birthday
}

void DayOfYear::get_dates() // Member Function


{
cout << "Enter a numeric month:";
cin >> month;
cout << " Enter a numeric day:"; Birth_year can be accessed because it is
cin >> day;
cout << " Enter a numeric Year:"; used within the member function
cin >> year;
}

void DayOfYear::output() // Member Function


{
cout << month << "/" << day << "/" << year << endl;
cout << birth_year << endl << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 344

Notes: 172
2006 C++ Course Handouts January 2006

Constructors
Used to initialize classes
Must be in the public section of the class
Cannot return a value (Must be void)
Must have same name as class
class BankAccount
{
public:
BankAccount(int dollars, int cents, double rate);
BankAccount(int dollars, double rate);
BankAccount(); // default constructor
voidoutput(ostream&, outs);
private:
double balance;
double interest_rate;
};

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 345

Constructors

int main(void)
{

BankAccount account1(100, 2.3); // Call the constructor


BankAccount account2; // Call default constructor
BankAccount account3(500, 99, 6.6); // Call a constructor

account3 = BankAccount(999, 99, 5.5);


account1 = BankAccount(1000, 7.6);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 346

Notes: 173
2006 C++ Course Handouts January 2006

Constructors

BankAccount::BankAccount(int dollars, int cents, double rate)


{
balance = dollars + 0.01 * cents;
interest_rate = rate;
}

BankAccount::BankAccount(int dollars, int rate)


{
balance = dollars;
interest_rate = rate;
}

BankAccount::BankAccount() // Default Constructor


{
balance = 0;
interest_rate = 0.0;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 347

Another Class Example (1 of 3)


#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;

class mathClass
{

public:
mathClass();
void add();
void subtract();
void multiply ();
void divide();
void getInput();
private:
double num1,num2,result;
};

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 348

Notes: 174
2006 C++ Course Handouts January 2006

Another Class Example (2 of 3)


mathClass::mathClass()
{
num1=0.0;
num2=0.0;
result=0.0;
}

void mathClass::getInput()
{
cout << "Jim's Math Machine.......\n\n";
cout << " Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
}

void mathClass::add()
{
result=num1+num2;
cout<<"The sum of the numbers is: "<<result<< endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 349

Another Class Example (3 of 3)


void mathClass::multiply()
{
result=num1*num2;
cout<<"The Product of the numbers is: " <<result<< endl;
}

void mathClass::subtract()
{
result=num1-num2;
cout<<"The Difference between the numbers is: "<<result<< endl;
}

void mathClass::divide()
{
result=num1/num2;
cout<<"The quotient of the numbers is: "<<result<< endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 350

Notes: 175
2006 C++ Course Handouts January 2006

Wrapper Class Example


#include <iostream>
#include <C:/progs/cpp/cis162/2005/mathClass.h>
using namespace std;

void main()
{
mathClass math;
math.getInput();
math.add();
math.subtract();
math.multiply();
math.divide();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 351

Review Questions
#include <iostream>
using namespace std;

structure book {
char title[30]; Find the error in the
char author[25];
int
float
quantity;
cost;
following structure
};

void main(void)
{
book library; // Structure Variable
cout << " Enter Book Title:";
cin >> library.title;
cout << "Enter Authors Name:";
cin >> library.author;
cout << " Enter Recent Cost:";
cin >> library.cost;

cout << library.title << " ";


cout << library.author << " ";
cout << library.cost << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 352

Notes: 176
2006 C++ Course Handouts January 2006

Review Questions
#include <iostream>
using namespace std;
Find the error in the
class DayOfYear
{
public:
following class
void output(); // member function prototype
void get_dates(); // member function prototype
int month;
int day;
int year;
private:
int birth_year;
};
DayOfYear today, birthday; // Declare abstract variables
void main(void)
{
today.get_dates(); // Load today
today.output(); // Dump today
birthday.get_dates(); // Load birthday
birthday.output(); // Dump birthday
cin >> today.birth_year;
}

void DayOfYear::get_dates() // Member Function


{
cout << "Enter a numeric month:";
cin >> month;
cout << " Enter a numeric day:";
cin >> day;
cout << " Enter a numeric Year:";
cin >> year;
birth_year = year-40;
}

void DayOfYear::output() // Member Function


{
cout << month << "/" << day << "/" << year << endl;
cout << birth_year << endl << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 353

Homework
1. Should have read Chapters 1 through 7 by now
2. Read Chapter 8 for next week
3. Work on your term paper

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 354

Notes: 177
2006 C++ Course Handouts January 2006

Chapter 7 Summary

Classes & Data Structures

Classes
Constructors
Structures
Initializing
Structures
Passing Structures as
Arguments

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 355

Chapter 8

Arrays, Single and Multidimensional

Single Dimension Arrays


Multi Dimension Arrays
Dynamic Arrays

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 356

Notes: 178
2006 C++ Course Handouts January 2006

Arrays

An array is used to process a collection of data


with the same data type.
Examples
List of test scores or temperatures
List of names or addresses

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 357

Arrays

Scalar Variables 1234


int count; Each
int day; 31 variable
float cost; of a
34.55
char letter; scalar
W takes one
Arrays location
int days[6];

0th 1st 2nd 3rd 4th 5th 6th

123 322 332 455 122 32 432

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 358

Notes: 179
2006 C++ Course Handouts January 2006

Arrays

Declaring an Array
#define SIZE 100
char name[25];
int counts[1000];
double prices[90];
int quan[SIZE];
int table[5][5];
char matrix[10][20];
unsigned short int mat[6][5];

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 359

Arrays

Declaring an Array Like declaring 5 different,


int score[5]; but similar variables.
Arrays work very well
Same As: when trying to do 1000’s
int score1; of declarations
int score2;
int score3;
int score4;
int score5;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 360

Notes: 180
2006 C++ Course Handouts January 2006

Internally, looks like this . . . .

0080 00000000 score[0]


0081 00000000
0082 00000000 score[1]
0083 00000000
0084 00000000 score[2]
0085 00000000 Assuming a 2-byte
0086 00000000 score[3] integer. Some machines
0087 00000000 now use 4 bytes for
0088 00000000 score[4]
0089 00000000
integers.
008A 00000000
008B 00000000
008C 00000000
008D 00000000

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 361

Common Error

Declaring an Array
int score[5];

score[5]; // index out of bounds

index = 12;
score[index];

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 362

Notes: 181
2006 C++ Course Handouts January 2006

Common Error
int counts[5] = {2,4,6,8,10};
int i = 1000;

for (i=0; i<=5; i++)


counts[i]=0;

0th 1st 2nd 3rd 4th i variable

Before 2 4 6 8 10 1000 0

0th 1st 2nd 3rd 4th i variable

After 0 0 0 0 0 0 0

Trouble Here

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 363

Arrays
January has 31 days.
February has 28 days.
March has 31 days.
April has 30 days.
May has 31 days.
#include <iostream>
June has 30 days.
#include <iomanip>
July has 31 days.
#include <string>
August has 31 days.
#define MONTHS 12
September has 30 days.
October has 31 days.
using namespace std;
November has 30 days.
December has 31 days.
void main()
{
string month[]={"January", "February", "March", "April", "May",
"June", "July", "August“, September", "October", "November", "December"};

int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
int i;

for (i=0; i<MONTHS; i++)


{
cout << setw(16) << left << month[i] << " has ";
cout << setw(4) << right << days[i] << " days.\n";
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 364

Notes: 182
2006 C++ Course Handouts January 2006

Arrays

#include <iostream>
#include <iomanip>
#include <string>
#define MONTHS 12 Enter the Month to Print(1-12): 2
You requested February
using namespace std;

void main()
{
string month[]= {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"};

int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
int month_input;

cout << "Enter the Month to Print(1-12): ";


cin >> month_input;

month_input--;
cout << "You requested " << month[month_input] << endl << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 365

Arrays

100 101 102 103 104 105 106 107 108 109

#include <iostream> // for cout


#include <iomanip> // for setw

void main() 0 100


{ 1 101
int numbers[10];
int i, x; 2 102
i = 0; 3 103
x = 100; 4 104
5 105
for (i=0; i<10; i++) 6 106
numbers[i]=x++; 7 107
8 108
for (i=0; i<10; i++) 9 109
cout << i << setw(5) << numbers[i] << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 366

Notes: 183
2006 C++ Course Handouts January 2006

Array Initialization
Code verified 11/17/2001
#include <iostream>
using namespace std;

void main()
{
int children[3] = {2, 12, 3};
char codes[4] = {'A', 'C', 'Z', '$'};
long vectors[] = {12, 23, 43, 54, 2, 99, 21};

int n;
int size;

// calculate the size of the vectors array


size = sizeof(vectors) / sizeof(long);
for (n=0; n<size; n++)
vectors[n]=0;

cout << sizeof(vectors) << endl; Also, can be read


cout << sizeof(long) << endl; in from a disk file
cout << size << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 367

Initializing Arrays

Initializing a one dimensional array of integers


int testscores[10] =
{98,87,88,89,90,100,76,99,91,81};

Initializing a two dimensional array of integers


int matrix[2][3] = {
{43,54,65},
{44,65,99}
}
int matrix[2][3] = {{43,54,65},{44,65,99}}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 368

Notes: 184
2006 C++ Course Handouts January 2006

Initializing Arrays

You initialize this array by writing


int theArray[5][3] =
{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }

For the sake of clarity, you could group the initializations


with braces. For example,
int theArray[5][3] =
{ {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}, {13,14,15} };

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 369

Common Error

Indexes always start at zero in C or C++


Called, zero relative
Most languages start at 1 (COBOL, VB, FORTRAN)

Fence Post Errors


It is so common to write to one past the end of an array that this bug has
its own name. It is called a fence post error. This refers to the problem in
counting how many fence posts you need for a 10-foot fence if you need
one post for every foot. Most people answer 10, but of course you need
11. (Excerpt from C++ in 21 days)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 370

Notes: 185
2006 C++ Course Handouts January 2006

Coding Practice

Use the const to make the size of the array

#include <iostream>
const int MAX_PEOPLE = 20;

main(void)
{
int array_employee_numbers[MAX_PEOPLE];
int n=0;
for (n=0; n<MAX_PEOPLE; n++)
array_employee_numbers[n]=0;

}
Code verified 11/17/2001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 371

Passing Arrays by Reference


#include <iostream>
#define SIZE 10

void dump_array(int ar[], int n);


int test_scores[SIZE] = {98,87,88,89,90,100,76,99,91,81};

int main(void) Generated Output


{ Score 0 is 98
dump_array(test_scores, SIZE); Score 1 is 87
Score 2 is 88
cout << "2 is " << test_scores[2] << endl; Score 3 is 89
return(0); Score 4 is 90
Score 5 is 100
} Score 6 is 76
Score 7 is 99
// Pass the address of the array and the size Score 8 is 91
Score 9 is 81
void dump_array(int ar[], int n) 2 is 200
{
int i;
for (i=0; i<n; i++)
cout << "Score " << i << " is " << ar[i] << endl;
ar[2]=200; // modify element 2
} Code verified 11/17/2001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 372

Notes: 186
2006 C++ Course Handouts January 2006

How Much Space Does an Array Take?

If you declared an array of 100 floats you would get 400 bytes of
contiguous memory allocated to the array. For example:

float array1[100];

Each element, (sometimes called buckets) of the array takes four


bytes because of the floating point space needed for one
variable. The compiler gives us 100 of these so 100 elements
times 4 bytes each gives 400 bytes internally for the array.
This same principle can be applied to integer, double, character
and long.
Be careful of type struct, though. There are some filler and
padding that takes place that is not visible to the programming
eye.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 373

Arrays and Structures


#include <iostream>
struct windinfo Let's print out some sizes
{
double velocity; Windinfo:16
char direction; Weather:1600
long temperature; Velocity:8
};
Direction:1
void main() Temperature:4
{
windinfo weather[100]; // Array of 100 windinfo
int x;
// initialize the structure members
for (x=0; x<100; x++) Code verified 11/17/2001
{
weather[x].velocity = 0;
weather[x].direction = 'S';
weather[x].temperature = 0;
}
cout << "Let's print out some sizes“ << endl;
cout << " Windinfo:" << sizeof(windinfo) << endl;
cout << " Weather:" << sizeof(weather) << endl;
cout << " Velocity:" << sizeof(double) << endl;
cout << " Direction:" << sizeof(char) << endl;
cout << "Temperature:" << sizeof(long) << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 374

Notes: 187
2006 C++ Course Handouts January 2006

Multidimensional Arrays

char page[30][100];
This array has two indexes
The first is from 0 to 29
the second is from 0 to 99
page[0][0], page[0][1] … page[0][99]
page[1][0], page[1][1] … page[1][99]
page[2][0], page[2][1] … page[2][99]

page[29][0], page[29][1] … page[29][99]

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 375

Arrays of Strings

char names[45][100];
char addresses[45][100];

These arrays have two indexes


The first is from 0 to 44, the second is from 0 to
99
names array holds data like:

Smith
Leonard
Wilson
Dotolo

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 376

Notes: 188
2006 C++ Course Handouts January 2006

Dynamic Arrays
#include <iostream>
using namespace std;

typedef int* Integer_Array;

void main(void)
{
int array_size=0;
int i=0;

cout << "Enter array size:";


cin >> array_size;
Integer_Array arr;
arr = new int[array_size];

for (i=0; i<array_size; i++)


arr[i]=i;

for (i=0; i<array_size; i++)


cout << arr[i] << endl;

delete [] arr;
} Code verified 11/17/2001

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 377

Review Questions
1. Arrays in C++ start at the __________ element?
2. Arrays of characters are sometimes called _____?
3. What is a common error when using arrays?
4. Find the errors in the following array declarations.
1. int array1(1000);
2. char name{45};
3. float costs[ ] = 12.99, 23.45, 45.12;
5. Find the errors in the following array statements.
1. array1[1001]=100;
2. name[-1]=‘a’;
3. costs(1)=12.98;

This section corresponds to Chapter 8 in the Text by Tony


Gaddis, Starting Out With C++, 4th Edition

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 378

Notes: 189
2006 C++ Course Handouts January 2006

Homework
1. Should have read Chapters 1 through 8 by now
2. Read Chapter 9 for next week
3. Work on your term paper

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 379

Chapter 8 Summary

Arrays Summary

Single Dimension
Multi Dimension
Static and Dynamic

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 380

Notes: 190
2006 C++ Course Handouts January 2006

Chapter 9 – Sorting & Searching

Sorting Searching Concepts

Exchange Sort
Selection Sort
Merge Sort
Quick Sort
Binary Search

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 381

Sorting an Array

Many types of sorting algorithms


Hash
Insertion
Bubble (Exchange)
Selection
Shell
Tournament
Shaker
Quick Sort
Merge Sort Sorting and Sort Systems
Poly-Phase
Cascade by Harold Lorin.
Oscillating
Crisscross

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 382

Notes: 191
2006 C++ Course Handouts January 2006

Clocking a C++ Program


The header file time.h includes definitions for:
1. a type clock_t, which is some integer type;
2. a function clock_t clock(), which returns the elapsed time since
its first call in some unit; and
3. a constant CLOCKS_PER_SEC, which gives the number of time
units (as returned by clock()) in one second.
In order to use the clock() function, a C or C++ program must
contain:

#include <time.h>
clock_t tv1, tv2;
double time;
tv1 = clock();

// insert code to time here

tv2 = clock();
time = (tv2 - tv1)/(CLOCKS_PER_SEC / (double) 1000.0);

In the above code, we compute time as a double in case


CLOCKS_PER_SEC is less than 1000
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 383

Bubble Sort (Exchange Sort)


Bubble Sort Algorithm
1. Compare element-0 with
element-1
2. If element-0 is greater than
element-1, then swap the
two elements
3. Continue on with element-1
and element-2
4. Continue on with element-2
and element-3
5. Elements are known as
element n and element n+1
6. Continue until the end of the
array is reached
7. Repeat steps 1 through 6
until no swaps are made
8. This algorithm is known as
an n2 algorithm
9. On an array of 10 it could
take as many as 100 swaps
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 384

Notes: 192
2006 C++ Course Handouts January 2006

Bubble Sort (Exchange Sort)


Bubble Sort Algorithm
Discussion
1. There are ways to “speed
up” the bubble sort
2. Inside the inner loop, test to
see if you swapped anything
3. If no swaps were made the
sort is finished. This will
usually cut the sort time in
half unless the data is
reversed from the start
4. Bubble sort is an n2
algorithm
5. Methods
1. Swap
2. Needs two loops, inner and
outer

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 385

Bubble Sort (1 of 3)
#include <iostream>
#include <time.h>
using namespace std;

void initialize_array(void);
int sort_it(int a[]);

const int SIZE = 10000;


int main_array[SIZE];

void main()
Know as the n-squared method
{
Also known as the exchange sort.
int swaps;
clock_t tv1, tv2;
double time;

initialize_array();
tv1 = clock();
swaps=sort_it(main_array);
tv2 = clock();
time = (tv2 - tv1)/(CLOCKS_PER_SEC / (double) 1000.0);

cout << "Swaps:" << swaps << endl;


cout << "Time:" << time << " milliseconds" << endl;
} // end of main

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 386

Notes: 193
2006 C++ Course Handouts January 2006

Bubble Sort (2 of 3)
// sort the array
int sort_it(int arr[])
{
int x, swap;
int swaps=0;
bool we_swapped_one=false;

// do the sort
do
{
we_swapped_one=false;
for (x=0; x<SIZE-1; x++)
{
if (arr[x]>arr[x+1])
{
swap=arr[x];
arr[x]=arr[x+1];
arr[x+1]=swap;
swaps++;
we_swapped_one=true;

}
} // end of inner for loop Know as the n-squared method
}
while (we_swapped_one); Also known as the exchange sort.
return(swaps);
} // end of function sort_it

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 387

Bubble Sort (3 of 3)

// Initialize the array with random numbers


void initialize_array()
{
int number;

for (int i=0; i<SIZE; i++)


{
number=rand();
number = number % 10000;
main_array[i]=number;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 388

Notes: 194
2006 C++ Course Handouts January 2006

Shaker Sort
Shaker Sort Algorithm Discussion
1. A Shaker Sort is bi-directional bubble sort
because we work from both ends
2. Alternate movements between 0 and n on one
pass to n and 0 on the next pass. This will move
an element right to the top or bottom depending
on which way you are moving.
3. It gets its name because of the way it moves
about the list, back and forth like a salt shaker or
the popular beverage mixer.
4. http://users.net1plus.com/brianl/ShakerSort.htm

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 389

Selection Sort
0 1 2 3 4
Selection Sort Algorithm

1. Starting at the 0th element, search for the


smallest element in the set 0 through n.
Exchange with the 0th element
2. Starting at element-1, search for the smallest
element in the range 1 through n. When
found, exchange with element-1
3. Starting at element-2, search for the smallest
in 2 through n. Exchange with the 2nd
element
4. Starting at element-3, search for the smallest
in 3 through n. Exchange with the 3rd
element
5. Continue until the nth element is reached

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 390

Notes: 195
2006 C++ Course Handouts January 2006

Selection Sort

Algorithm
1. Find the smallest element in the
set 0-n
2. Exchange with the zero element
3. Find the smallest in 1-n
4. Exchange with the 1st element
5. Find the smallest in 2-n
6. Exchange with the 2nd element
7. Find the smallest in 3-n
8. Exchange with the 3rd element
9. Continue until the n-th element
is reached

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 391

Selection Sort
Selection Sort Discussion
Methods
1. Search for the lowest element starting from nth element
2. Swap the lowest element with nth element

The insertion sort is considered to be an n2 algorithm

180

150

120

90

60

30

10 20 30 40 50 60 70 80 90 100
N (thousands)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 392

Notes: 196
2006 C++ Course Handouts January 2006

Selection Sort Code (1 of 3)


#include <iostream>
#include <time.h>
using namespace std;

void initialize_array(void);
int sort_it(int a[]);

const int SIZE = 10000;


int main_array[SIZE];

void main()
{

int swaps;
clock_t tv1, tv2;
double time;

initialize_array();
tv1 = clock();
swaps=sort_it(main_array);
tv2 = clock();
time = (tv2 - tv1)/(CLOCKS_PER_SEC / (double) 1000.0);

cout << "Swaps:" << swaps << endl;


cout << "Time:" << time << " milliseconds" << endl;
} // end of main

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 393

Selection Sort Code (2 of 3)


// Function to Perform the Selection Sort
int sort_it(int array[])
{
int startScan, minIndex, minValue, swaps=0;

for (startScan = 0; startScan < (SIZE - 1); startScan++)


{
minIndex = startScan;
minValue = array[startScan];
for(int index = startScan + 1; index < SIZE; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
swaps++;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
return(swaps);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 394

Notes: 197
2006 C++ Course Handouts January 2006

Selection Sort Code (3 of 3)


// Initialize the array with random numbers
void initialize_array()
{
int number;

for (int i=0; i<SIZE; i++)


{
number=rand();
number = number % 10000;
main_array[i]=number;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 395

Sort Animation Web Site


Demonstration of Selection, Bubble, Insertion,
Heap, Merge and Quick Sorts

http://www.ship.edu/~cawell/Sorting/selintro.htm

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 396

Notes: 198
2006 C++ Course Handouts January 2006

Searching an Array

Picture a phonebook
How would you find a number by
name?
¾ Search alphabetically
How would you find a name by using a
number?
¾ Search linearly
Linear Search
¾ Start at the beginning and test every
occurrence
Binary Search
¾ Sort the data
¾ Successive slicing in half

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 397

Searching an Array Sequentially

Sequential Search
#include <string.h>
#include <iostream>
using namespace std;
int k, size;
int a[]={32,43,54,65,90,21,23,34,45,65, 67,879, 89, 200,
33, 41, 34};
Output
int main(void)
{ Hit:32
size = sizeof(a) / sizeof(int);
Hit:43
for (k=0; k<size; k++)
{ Hit:21
if (a[k] < 50)
cout << "Hit:" << a[k] << endl; Hit:23
}
return(0); Hit:34
}
Hit:45
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 398

Notes: 199
2006 C++ Course Handouts January 2006

Binary Search
Say we have 100 million phone numbers
Sort the numbers
If we are looking for 555-480-9400
To see how many tests we need we need
to use logarithms
Searches = log2x, where x is the total number of items
Searches = log2100000000 for example

How to solve:
Searches = Log10100000000 / Log102
Searches = 8 / 0.301029996
Searches = 26.57 or rounded up to 27

From Log conversion formula (Applied Mathematics, p 1.6)


logb(x) = loga(x)/loga(b)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 399

Binary Search
First, Sort the data
Then, by successively cutting the array of data in half, you can narrow
down the search
1. Say we are looking for 303
2. See how any elements are in the array
3. Choose the middle position (5 in this case)
4. Compare the value at 5 (333) against the search argument (303)

Num(0) 204
Num(1) 222
Num(2) 303
Num(3) 321
Num(4) 324
Num(5) 333 Middle Position
Num(6) 356
Num(7) 411
Num(8) 444
Num(9) 504
Num(10) 621
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 400

Notes: 200
2006 C++ Course Handouts January 2006

Binary Search Example ( 1 of 4)


int binarySearch(int [], int, int);
void initialize_array(void);
int sort_it(int a[]);

const int SIZE = 10000;


int main_array[SIZE];

void main()
{
int results, empID=1, swaps;

initialize_array();
swaps=sort_it(main_array);
cout << "Swaps:" << swaps << endl;

while( empID != 0)
{
cout << "Enter the employee ID you wish to search for: ";
cin >> empID;
results = binarySearch(main_array, SIZE, empID);
if (results == -1)
cout << "That number does not exist in the array.\n";
else
{
cout << "That ID is found at element " << results;
cout << " in the array.\n";
}
} // end of while loop
} // end of main

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 401

Binary Search Example ( 2 of 4)


// Binary Search Function
int binarySearch(int array[], int num, int value)
{
int last = num - 1;
int first = 0;
int middle;
int position = -1;
bool found = false;

while (!found && first <= last)


{
middle = (first + last) / 2; // Calculate midpoint

if (array[middle] == value) // If value is found at midpoint


{
found = true;
position = middle;
}
else if (array[middle] > value) // If value is in lower half
last = middle - 1;
else
first = middle + 1; // If value is in upper half
}

return position;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 402

Notes: 201
2006 C++ Course Handouts January 2006

Binary Search Example ( 3 of 4)

// Initialize the array with random numbers


void initialize_array()
{
int number;

for (int i=0; i<SIZE; i++)


{
number=rand();
number = number % 10000;
cout << number << endl;
main_array[i]=number;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 403

Binary Search Example ( 4 of 4)


// sort the array
int sort_it(int arr[])
{
int x, swap;
int swaps=0;
bool we_swapped_one=false;

// do the sort
do
{
we_swapped_one=false;
for (x=0; x<SIZE-1; x++)
{
if (arr[x]>arr[x+1])
{
swap=arr[x];
arr[x]=arr[x+1];
arr[x+1]=swap;
swaps++;
we_swapped_one=true;
}
} // end of inner for loop
}
while (we_swapped_one);
return(swaps);
} // end of function sort_it

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 404

Notes: 202
2006 C++ Course Handouts January 2006

Indexed Files and SQL Indexes

1. An Indexed File has two, or more, parts


2. Data is kept in the Data Part in Birth Order
3. A separate file of keys is maintained for each key field (index field)
4. Sometimes there can be several key files
Data Part

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 405

Chapter 9 Summary

Sorting and Searching

Bubble Sorts
Selection Sorts
Binary Search

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 406

Notes: 203
2006 C++ Course Handouts January 2006

Chapter 10 – C++ Strings

Character Arrays & String Class

Strings
Character Arrays
String Functions
String Class

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 407

String Basics

A String Literal: cout << “Hello”

A cstring variable: char book_title[30];

Null Character, \0
Also known as low-values

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 408

Notes: 204
2006 C++ Course Handouts January 2006

String Function Preview


gets() puts()
strcat() strcpy()
strcmp() strstr()
isalnum() isalpha()
iscntrl() isdigit()
isgraph() strupr()
islower() isprint()
ispunct() isspace()
isupper() isxdigit()
toupper() tolower()
memset() memcpy()
ctype.h string.h

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 409

String Data
Strings in C++ are no more
than an array of characters.
#include <iostream>
using namespace std;
char name[40]; // 40 characters
char address[50]; // 50 characters
char state[3];

int main(void) 0 is same as null is same as ‘\0’


{
state[0]=‘A’;
state[1]=‘Z’;
state[2]=0;
strcpy(name, ”Will Smith ”);
strcpy(address, “1234 W. Pecos ”);
cout << name << address << state << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 410

Notes: 205
2006 C++ Course Handouts January 2006

String Data Using C++


#include <iostream>
using namespace std; Strings in C++ are no more
than an array of characters.
void main()
{
char sentence[] = "Hello World";
int count = 0;

for (int i = 0; sentence[i] != '\0'; i++)


{
count++;
}

cout << "The string " << sentence << " has " << count
<< " characters and is stored in " << count+1 << " bytes\n";

}
0 is same as null is same as ‘\0’
Output:
The string Hello World has 11 characters and is stored in 12 bytes

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 411

Strings in C++
char name[20] = “SMITH “;

terminated with low-values or binary zero \0


called ASCIIZ strings
¾ ASCII Data Followed by a Binary Zero
string functions will insert appropriate \0 (NULL)
if you are building your own strings, you must insert \0
strings are zero relative

Example:
name[5]=‘\0’; // optionally name[5]=0;
cout << name << endl’

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 412

Notes: 206
2006 C++ Course Handouts January 2006

Strings in C++

Examples of string declarations

char name[20] = “SMITH \0“;


char address[30];
char zip_code[5];
char input_area[1000];
Computer Memory is sequential and linear

C I S 1 6 2 \0

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 413

Difference Between \0 and “0”


Binary Zero 00000000 NULL or \0
ASCII Zero 00110000 48 or Character Zero

0 48 00110000
1 49 00110001
2 50 00110010
3 51 00110011
4 52 00110100
5 53 00110101
6 54 00110110
7 55 00110111
8 56 00111000

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 414

Notes: 207
2006 C++ Course Handouts January 2006

ASCII v. Numeric 32
! 33
" 34
# 35
#include <iostream> $ 36
using namespace std; % 37
& 38
' 39
void main() ( 40
{ ) 41
int counter; * 42
+ 43
, 44
for (counter=32; counter<255; counter++) - 45
{ . 46
cout.width(1); / 47
0 48
cout << (char) counter; 1 49
cout.width(4); 2 50
cout << counter << endl; 3 51
4 52
}
5 53
} 6 54
7 55

Code verified 11/23/2003

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 415

ASCII v. Numeric

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 416

Notes: 208
2006 C++ Course Handouts January 2006

String or Character

char ch;
ch = ‘A’; // character A stored in memory
ch = “A”; // character A followed by \0
ch = A; // loads ch with the variable A

ASCII
American Standard Code for Information Interchange

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 417

String Literals

A set of characters
“string literal” wrapped on double quotes
¾ Characters wrapped in single quotes
¾ Strings wrapped in double quotes
Also called a character array
Max length ANSI, is 509 bytes
Max length, Microsoft, is 2008 bytes
Always end with NULL (Binary Zero, \0)
cout << “This is a string literal..”;
char msg1[]=“This is a C string literal”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 418

Notes: 209
2006 C++ Course Handouts January 2006

strcpy() -- Assigning a Value to a String

char msg1[]=“This is a C++ string”;


char msg2[]=“Also Called Character Arrays”;

Or

strcpy(msg1, “This is a C++ string”);


strcpy(msg1, msg2);

C++ Prototype
char strcpy(char *str1, char *str2)

Copy contents of str2 to str1. Str2 must be a NULL-


terminated string. ( ASCIIZ string )

strcpy(address, “2626 E. Pecos Rd.”);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 419

strncpy()

prototype
strncpy(strcpy(char *str1, char *str2, int count)

Examples
strncpy(str1, str2, count)
strncpy(str1, str2, count+1)
strncpy(str1, str2, 12)
Note:
if str1 cannot hold the contents of str2 then
behavior is undefined.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 420

Notes: 210
2006 C++ Course Handouts January 2006

strcat() – String Concatenation


char strcat(char *str1, char *str2)

Concatenates a copy of str2 onto str1. Str2 must be a NULL-


terminated string. ( ASCIIZ string )

Let’s assume we have…


char address_1[13]=“2626 E. Pecos”;
char address_2[17]=“Gilbert, AZ 85234”;
char address_3[50];

strcpy(address_3, address_1);
strcat(address_3, address_2);

Address_3 Now Contains:


2626 E. Pecos Rd. Gilbert, AZ 85234

str2 is untouched by the operation.


No bounds checking is performed. Programmer must do this.
Programmer must ensure str1 will hold str2.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 421

strncat() – String Concatenation


char strncat(char *str1, char *str2, int count)

Concatenates a copy of str2 onto str1. Str2 must be a


NULL-terminated string. ( ASCIIZ string )

Let’s assume we have…


char address_1[13]=“2626 E. Pecos”;
char address_2[17]=“Gilbert, AZ 85234”;
char address_3[50];

strncpy(address_3, address_1, 13);


strncat(address_3, address_2, 17);

Address_3 Now Contains:


2626 E. Pecos Rd. Gilbert, AZ

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 422

Notes: 211
2006 C++ Course Handouts January 2006

strcmp() – String Comparison


Prototype
int strcmp(char *str1, char *str2)
char message[]="This is a string";
// Method One
if (strcmp(message, "This is a string")) Returns
cout << "Strings are NOT the same\n"; < 0: str1 is less than str2
else = 0: str1 = str2
cout << "Strings are the same\n"; > 0: str1 is greater than str2

// Method Two
if (strcmp(message, "This is a string") == 0)
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";

// Method Three
if (! strcmp(message, "This is a string"))
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 423

strncmp() – String Comparison


Prototype
int strncmp ( const char * string1, const char * string2, int num );
char message[]="This is a string";
// Method 1
if (strncmp(message, "This is", 7))
Returns
cout << "Strings are NOT the same\n"; < 0: str1 is less than str2
else = 0: str1 = str2
cout << "Strings are the same\n"; > 0: str1 is greater than str2

// Method 2
if (strncmp(message, "This is a", 9) == 0)
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";

// Method 3
if (! strncmp(message, "This", 4))
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 424

Notes: 212
2006 C++ Course Handouts January 2006

Common Error

A common error in C++ programming is to attempt to


set a variable to a string literal using the assignment
operator.

This is Illegal with Character Arrays


message = “This is a string”;

Proper method:
strcpy(message, “This is a string”);
strcpy(message, myString);

Assume:
char message[40]=“Test String One”;
char myString[40]=“My String Data”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 425

Common Error

A common error in C++ programming is to attempt to


compare string variables using the if command.

This is Illegal:
if (message == “This is a string”)
do_something; < 0: str1 is less than str2
= 0: str1 = str2
> 0: str1 is greater than str2
Proper method:
if (strcmp(message, “This is a string”))
cout << “Strings are NOT the same”;
else
cout << “Strings are the same”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 426

Notes: 213
2006 C++ Course Handouts January 2006

strlen() function

char name[25] = “Ada Lovelace”;


int x;
x = strlen(name);

x should contain the number of characters in name.

Remember:
sizeof() shows the length of the variable space
strlen() shows the actual length of the string contents

Ada Lovelace Born: London, England, December 10, 1815


Died: London, England, November 27, 1852
Analyst, Metaphysician, and Founder of Scientific Computing

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 427

Application
One use for strlen()
To test for an empty input string. Examples:
int x;
cin >> name;
x = strlen(name);
if (x == 0)
{
cout << “Invalid Named Entered \n”;
}

or

if (strlen(name) == 0)
{
cout << “Invalid Named Entered \n”;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 428

Notes: 214
2006 C++ Course Handouts January 2006

getchar()
reads a character from the keyboard

#define LF 10
int count;
char name[30];
int main(void)
{
count=0;
while (count < 30)
{
name[count] = getchar();
if (name[count] == LF)
{
name[count]=0;
break;
}
count++;
}
cout << name << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 429

putchar()
writes a character to the screen (stream I/O)
#include <iostream.h> // for cout
#include <stdio.h> // for putchar
#include <string.h> // for strlen
int x, length;
char name[30]="Samira Munoz\0";
void main(void)
{ Code verified 11/17/2001
x=0;
length=strlen(name);
// Write the name once
while (x < length)
{
putchar(name[x]);
x++;
}
// Write the name again
cout << endl << name << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 430

Notes: 215
2006 C++ Course Handouts January 2006

getchar() & putchar() Combo

#include <stdio.h> // for putchar & getchar

char ch;
void main(void)
{
while ((ch = getchar()) != EOF)
putchar(ch);

This is only a test[ENTER]


Code verified 11/17/2001
This is only a test

EOF is typically -1 when reading data files


CTRL-Z for PC keyboard input
CTRL-D for Unix keyboard input

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 431

puts() and gets()

Quick and dirty way to obtain text from


keyboard and print text to the screen.

puts(stringvar);
puts(“Literal”);
gets(stringvar);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 432

Notes: 216
2006 C++ Course Handouts January 2006

toupper() and tolower()


int toupper(int ch) // prototype
int tolower(int ch) // prototype

Returns the uppercase equivalent of ch if ch is a letter


otherwise ch remains unchanged.
char ch;
ch = ‘w’;
ch = toupper(ch);
cout << ch;

Returns the lowercase equivalent of ch if ch is a letter


otherwise ch remains unchanged.
char ch;
ch = ‘Q’;
ch = tolower(ch);
cout << ch;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 433

Getline Member Function

Member function to read a line of input


Syntax:
input_stream.getline (string_var, Max_Characters + 1);

Examples:
char st[30];

cin.getline(st, 30);
cin.getline(st, sizeof(st));

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 434

Notes: 217
2006 C++ Course Handouts January 2006

toupper() and tolower() Returns an Int


int toupper(int ch) /* prototype */
int tolower(int ch) /* prototype */

ch = ‘a’;
cout << toupper(ch); // Prints 65

ch = ‘a’;
cout << tolower(ch); // Prints 97

Why ?
toupper and tolower return integer results
Be Careful when embedding
these functions in the cout object

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 435

toupper() and tolower()


int toupper(int ch) /* prototype */
int tolower(int ch) /* prototype */

ch = ‘a’;
cout << (char) toupper(ch); // Prints A

ch = ‘A’;
cout << (char) tolower(ch); // Prints a

// Less confusing way. . .


ch = ‘A’;
ch = tolower(ch);
cout << ch; // Prints a

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 436

Notes: 218
2006 C++ Course Handouts January 2006

islower() and isupper()


int islower(int ch)

Returns nonzero value if ch is a lower case letter(a-z), otherwise


returns zero.
char ch;
ch = getchar();
if (islower(ch))
puts(“Lowercase Letter Found”);

int isupper(int ch)

Returns nonzero value if ch is an upper case letter(A-Z), otherwise it


returns zero.
char ch;
ch = getchar();
if (isupper(ch))
puts(“Uppercase Letter Found”);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 437

isalnum() & isalpha()


int isalnum(int ch) /* Alphanumeric Test */
Returns non-zero value if its argument is either a letter or a digit.
Non-zero means true.
char ch;
ch = getchar();
if (isalnum(ch))
cout << “Alphanumeric Character Found”;

int isalpha(int ch) /* Alphabetic Test */


Returns non-zero value if its argument is a letter.
char ch;
ch = getchar();
if (isalpha(ch))
cout << “Alphabetic Character Found”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 438

Notes: 219
2006 C++ Course Handouts January 2006

ispunct() & isspace()


int ispunct(int ch) // Punctuation Test
// Returns non-zero value if ch is a punctuation character.
!@#$%^&*()_-+= etc

char ch;
ch = getchar();
if (ispunct(ch))
cout << “Punctuation Character Found”;

int isspace(int ch) // Space Test


// Returns non-zero value if ch is a space character( hex
20).

char ch;
ch = getchar();
if (isspace(ch))
cout << “We have a Space Character”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 439

isxdigit() & isascii()

int isxdigit(int ch) // Hex Digit Test


// Returns non-zero value if ch is A-F, a-f or 0-9.

char ch;
ch = getchar();
if (isxdigit(ch))
cout << “Hex Digit Encountered”;

int isascii(int ch) // ASCII Char Test


// Returns non-zero value if ch is between 0 and hex
7F, otherwise returns 0.
char ch;
ch = getchar();
if (isascii(ch))
cout << “ASCII Character Encountered”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 440

Notes: 220
2006 C++ Course Handouts January 2006

iscntrl() & isdigit()

int iscntrl(int ch) /* Control Char Test */


Returns non-zero value if ch is between 0 and hex 1F or
hex 7F (DEL), otherwise returns 0.
char ch;
ch = getchar();
if (iscntrl(ch))
cout << “Control Character Found”;

int isdigit(int ch) /* Digit Test */


Returns non-zero value if ch is a digit, otherwise returns
a zero.
char ch;
ch = getchar();
if (isdigit(ch))
cout << “We have a Number”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 441

atoi(), atol(), atof(), itoa()

ASCII to Integer Conversion Function.


Takes in a string argument and returns its integer
equivalent
Also: atol & atof
Syntax:
int atoi(string_var); Pronounced:
A to I, A to L, A to F
Example:
void main()
{
int x=0; itoa for integer to ASCII
char st[7]="654321";
x = atoi(st);
cout << "Length of String: " << sizeof(st) << endl;
cout << "Length of x: " << sizeof(x) << endl;
}

Length of String: 7
Length of x: 4
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 442

Notes: 221
2006 C++ Course Handouts January 2006

atoi(), atol(), atof()


#include <iostream.h> // for cout
#include <stdlib.h> // for atoi, etc
int x; Code verified 11/17/2001
float y;
long z;
char int_st[12];
char float_st[12];
char long_st[12];
void main(void)
{
cout << "Enter some numbers" << endl;
cin >> int_st;
cin >> float_st;
cin >> long_st;
x=atoi(int_st);
y=atof(float_st);
z=atol(long_st);
x*=2;
y*=2;
z*=2;
cout << x << endl;
cout << y << endl;
cout << z << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 443

strupr()

char strupr(char *str) // prototype

Converts the string pointed to by str to uppercase.

char name[20]=“Charles Babbage\0”;


int main(void)
{

strupr(name);
cout << name << endl;

prints
CHARLES BABBAGE

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 444

Notes: 222
2006 C++ Course Handouts January 2006

strlwr()

char strlwr(char *str) // prototype

Converts the string pointed to by str to lowercase.

char name[20]=“Charles Babbage\0”;


int main(void)
{

strlwr(name);
cout << name << endl;

prints
charles babbage

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 445

Let’s See What We Know…


#include <stdio.h>
#include <ctype.h>
#include <string.h>
char fname[20];
char lname[20];
char full_name[60];
void main(void)
{
puts("Enter your First Name");
gets(fname);
puts("Enter your Last Name ");
gets(lname);
if (islower(fname[0]))
fname[0]=toupper(fname[0]);
if (islower(lname[0]))
lname[0]=toupper(lname[0]);
strcpy(full_name,fname);
strcat(full_name, “ “);
strcat(full_name,lname);
puts(full_name);
strupr(full_name);
puts(full_name);
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 446

Notes: 223
2006 C++ Course Handouts January 2006

strstr()
char strstr(char *str1, char *str2)
Returns a pointer to the first occurrence in str1 of the string pointed to by
str2.

char *p;
p = strstr(“This is a test”, ”te”);
if (p == 0)
cout << “No Find”;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 447

strspn Function
/* STRSPN.C: This program uses strspn to determine
* the length of the segment in the string "cabbage"
* consisting of a's, b's, and c's. In other words,
* it finds the first non-abc letter. */

#include <string.h>
#include <stdio.h>

void main( void )


{
char string[] = "cabbage";
int result;
result = strspn( string, "abc" );
printf( "The portion of '%s' containing only a, b, or c "
"is %d bytes long\n", string, result );
}

Generated Output
The portion of 'cabbage' containing only a, b, or c is 5 bytes
long
Courtesy MSDN Online

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 448

Notes: 224
2006 C++ Course Handouts January 2006

memset() & memcpy()


void memset(void *buf, char ch, unsigned count)
// Copies ch to memory area pointed to by buf, count
times.

char array[1000];
memset(array, ‘ ‘, 1000);

void memcpy(void *dest, void *src, unsigned count)


// Copies count characters from src to dest.

char array[1000];
char buffer[1000]; Not in Book
memcpy(array, buffer, 1000);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 449

String Class
#include <string>
Code Verified
#include <iostream>
10/29/2002
using namespace std;

void main(void)
{
string first_name, last_name;
first_name="Abraham";
last_name="Lincoln";
cout << first_name << " " << last_name << endl;
cout << first_name.capacity();
cout << "\n\n\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 450

Notes: 225
2006 C++ Course Handouts January 2006

String Class
Member Functions
At
Append
Assign
Begin
Copy
Capacity
Compare
End
Erase
Find
Insert
Length
Replace
Size
Swap
Substr

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 451

String Class
#include <string>
#include <iostream>
using namespace std;
int main(void) Generated Output
{
string first_name, last_name; Allen 5 31
string whole_name;
Shepard, Allen
first_name="Allen";
last_name="Shepard"; Shepard Allen
whole_name=last_name;
whole_name.append(", "); Shepard
whole_name.append(first_name);

cout << first_name << " ";


cout << first_name.length() << " ";
cout << first_name.capacity() << endl;
cout << whole_name << endl;

whole_name.at(7)=' '; // spaces out the comma


cout << whole_name << endl;

whole_name.at(7)=0; // chops off the last name


cout << whole_name << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 452

Notes: 226
2006 C++ Course Handouts January 2006

String Class
#include <string>
#include <iostream>
using namespace std; Generated Output
void main(void) Shpard, Al
{
string first_name, last_name; 3
string whole_name;
long ptr;
ShpQrd, Al
first_name="Allen";
last_name="Shepard";
whole_name=last_name;
whole_name.append(", ");
// append starting at 0, for 2 bytes
whole_name.append(first_name,0,2);
// erase 1 char starting pos 2, compress the str
whole_name.erase(2,1);
cout << whole_name << endl;
ptr = whole_name.find("ar");
cout << ptr << endl;
if (ptr > whole_name.capacity())
cout << "Cannot find selected substring\n\n";
else
{
whole_name.at(ptr) = 'Q';
cout << whole_name << endl;
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 453

Review Questions
1. Strings in C++ are simply ___________ arrays
2. A binary zero is 000000002 or 001100002
3. String Literals are wrapped with ______ quotes
4. The strlen() function can be used to __________
5. strcat() does what?
6. strcpy does what?
7. Explain isupper()
8. Explain tolower()
9. Explain atoi()
10. What String Class Member Function can be used to concatenate
two strings
11. What String Class Member Function can be used to replace a
specific character in a string

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 454

Notes: 227
2006 C++ Course Handouts January 2006

Homework
1. Should have read Chapters 1 through 10 and 12 by now
2. Work on your term paper
3. Work on Packet-3…

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 455

Chapter 12 Summary

String Class

Everything you ever wanted to Strings


String Functions
know about C++ string C++ String Class
manipulation, but were afraid
to ask.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 456

Notes: 228
2006 C++ Course Handouts January 2006

Chapter 13

Files, I/O Streams, Advanced I/O

Stream I/O
Character I/O
Inheritance

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 457

C++ General I/O


Data stored in disk files
C++ used to read in and write out data
Programs “read in” data from a file to a program
Programs “write out” data from the program to a
disk file
In other words, the I/O is program relative

C++
Program Disk File

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 458

Notes: 229
2006 C++ Course Handouts January 2006

File and Record Hierarchy


1. Databases contain sets of related files
2. Files contain records
3. Records contain fields
4. Fields contain characters (bytes)
5. Bytes are made up of bits
6. Bits

Think of a File Cabinet (Database)


Contains Drawers (Files)
Contains Folders (Records)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 459

Introduction to Files (Writing)


#include <fstream>
using namespace std;

void main(void)
{
ofstream outstream; // output file object

outstream.open("c:/myfile.dat");
outstream << "Albert Einstein\n"; Albert Einstein
outstream << "Michael Faraday\n"; Michael Faraday
outstream << "Alexander Graham Bell\n"; Alexander Graham Bell
Jimi Hendrix
outstream << "Jimi Hendrix\n"; Kurt Cobain
outstream << "Kurt Cobain\n";
outstream.close();
}

Code Verified 05/12/2003

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 460

Notes: 230
2006 C++ Course Handouts January 2006

Introduction to Files (Reading)


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void main(void)
{
ifstream instream; // output file object
string celebrity;

instream.open("c:/myfile.dat"); Albert Einstein


getline(instream,celebrity); Michael Faraday
cout << celebrity << endl; Alexander Graham Bell
getline(instream,celebrity); Jimi Hendrix
cout << celebrity << endl;
getline(instream,celebrity);
cout << celebrity << endl;
getline(instream,celebrity);
cout << celebrity << endl;
instream.close(); Code Verified 05/12/2003
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 461

Setting up C++ Stream I/O


Defining I/O Streams
#include <fstream.h>
int main(void)
{
ifstream instream;
ofstream outstream;

instream.open(“c:/myfile.dat”,ios::in|ios::nocreate);
instream.close();
}

Stream I/O is simply record processing.


It reads and writes sets, or groups, of data.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 462

Notes: 231
2006 C++ Course Handouts January 2006

Example of the fstream object


#include <iostream>
#include <fstream>
using namespace std;

int main()
{
fstream dataFile;
string buffer;

dataFile.open("myfile.dat", ios::out); // Open for output


dataFile << "Now is the time for all good men" << endl
<< "to come to the aid of their country.";
dataFile.close();
dataFile.open("myfile.dat", ios::in); // Open for reading
getline(dataFile, buffer); // Get first line
cout << buffer << endl; // Output first line
getline(dataFile, buffer); // Get second line
cout << buffer << endl; // Output second line
dataFile.close();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 463

Copying a Portion of a File


#include <fstream>
#include <string>
using namespace std;
Example reading a file
in and writing it out.
void main(void)
{
int i;
string record_in;
ifstream file_in;
ofstream file_out;
file_in.clear(); // clears all error codes
file_in.open("C:/data/numbers.txt", ios::in);
file_out.open("C:/data/Newfile.txt", ios::out);
for (i=0; i<100; i++)
{
file_in >> record_in;
if (file_in.fail() != 0) break;
file_out << record_in << endl;
}
file_in.close(); Code verified 11/23/02
file_out.close();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 464

Notes: 232
2006 C++ Course Handouts January 2006

File Open Short Cut


Input and output to text files are handled by including the header file
"fstream.h" and by then declaring variables of type ifstream and
ofstream respectively. For example, the following program reads
from a file named “myFile.dat" and writes to a file named
“yourFile.dat":

#include <iostream>
#include <fstream.h>
using namespace std;
void main()
{
char c;
ifstream infile(“myfile.dat");
ofstream outfile("yourFile.dat");
if (outfile && infile) // They will be 0 on err.
while (infile >> c)
outfile << c;

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 465

C++ Stream I/O


Variations on syntax

char filestring[25]=“C:/MYFILE.DAT”;
char filename[45]=“D:/INV/MASTER.DAT”;
ifstream file_in, filex, payroll_master;
ofstream file_out, newfile, inventory_detail;

payroll_master.open(filestring, ios::in|ios::nocreate);
inventory_detail.open(filename, ios::app);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 466

Notes: 233
2006 C++ Course Handouts January 2006

Mode Flags
The open Function for Output Streams
To use an output file stream (ofstream), you must associate that stream with a
specific disk file in the constructor or the open function. If you use the open
function, you can reuse the same stream object with a series of files. In either
case, the arguments describing the file are the same.

When you open the file associated with an output stream, you generally specify
an open_mode flag. You can combine these flags, which are defined as
enumerators in the ios class, with the bitwise OR ( | ) operator.

Flag Function
ios::app Opens an output file for appending.
ios::ate Opens an existing file (either input or output) and seeks the end.
ios::in Opens an input file. Use ios::in as an open_mode for an ofstream file to
prevent truncating an existing file.
ios::out Opens an output file. When you use ios::out for an ofstream object
without ios::app, ios::ate, or ios::in, ios::trunc is implied.
ios::nocreate Opens a file only if it already exists; otherwise the operation fails.
ios::noreplace Opens a file only if it does not exist; otherwise the operation
fails.
ios::trunc Opens a file and deletes the old file (if it already exists).
ios::binary Opens a file in binary mode (default is text mode).

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 467

File Append Example


#include <fstream>
using namespace std;

void main()
{
fstream dataFile;

dataFile.open("demofile.txt", ios::out);
dataFile << "Jones\n";
dataFile << "Smith\n";
dataFile.close();
dataFile.open("demofile.txt", ios::out|ios::app);
dataFile << "Willis\n";
dataFile << "Davis\n";
dataFile.close();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 468

Notes: 234
2006 C++ Course Handouts January 2006

Dot Operator

Objects

Calling Object.Member Function (Arguments);


Examples:
payroll_master.open(filestring);
inventory_detail.open(filename);
out_stream.precision(2);
File_in.get(ch);
File_out.put(ch);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 469

Other I/O Functions

Error Processing Functions


Use these member functions to test for errors while writing to a stream:

Function Return value


bad() Returns TRUE if there is an unrecoverable error.
fail() Returns TRUE if there is an unrecoverable error or an “expected”
condition, such as a conversion error, or if the file is not found.
Processing can often resume after a call to clear with a zero argument.
good() Returns TRUE if there is no error condition (unrecoverable or
otherwise) and the end-of-file flag is not set.
eof() Returns TRUE on the end-of-file condition.
clear() Sets the internal error state. If called with the default arguments,
it clears all error bits.
rdstate() Returns the current error state. For a complete description of
error bits, see the Class Library Reference

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 470

Notes: 235
2006 C++ Course Handouts January 2006

fail() Example
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

void main(void)
{
int i;
string data;
int count=0;

ifstream payroll_file;
payroll_file.clear();
payroll_file.open("C:/data/cpp/cis162/spring2003/numbers.txt", ios::in);

if (payroll_file.fail() != 0)
{
cout << "File Open Failed with Error Code: ";
cout << payroll_file.fail() << "\n";
cout << "Program Aborting...\n\n";
exit(1);
} Code Verified 11/23/02
for (i=0; i<10000; i++)
{
payroll_file >> data;
if (payroll_file.fail() != 0)
break;
count++;
}
cout << count << " Records processed...\n\n";
payroll_file.close();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 471

good() and append Example


string num;
string data_file="c:/data/cpp/cis162/spring2003/numbers.txt";
string new_file="c:/data/cpp/cis162/spring2003/newdata.dat";

void main(void)
{
ifstream numbers_in;
ofstream numbers_out;

// Open the input file


numbers_in.open(data_file.c_str(), ios::in);
if (numbers_in.good() == false)
{
cout << "Error Opening input File " << data_file << " \n\n";
exit(1);
}

// Open the output file for append


numbers_out.open(new_file.c_str(), ios::app);
if (numbers_out.good() == false)
{
cout << "Error Opening Output File " << new_file << " \n\n";
exit(1);
}

// Read and write the data


while (! numbers_in.eof()) Code Verified 11/23/02
{
numbers_in >> num;
numbers_out << num << endl;
cout << setw(8) << num << setw(3) << numbers_in.rdstate() << endl;
}

// Close the files


numbers_in.close();
numbers_out.close();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 472

Notes: 236
2006 C++ Course Handouts January 2006

eof() Example
#include <stdlib.h>
#include <iomanip> Code Verified 11/23/2002
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

string data;
long num;

void main(void)
{
ifstream payroll_file;
payroll_file.open("c:/data/cpp/cis162/spring2003/numbers.txt", ios::in);
if (payroll_file.fail() != 0)
{
cout << "File Open Failed with Error Code: ";
cout << payroll_file.fail() << "\n";
cout << "Program Aborting...\n\n";
}
else
{
while (! payroll_file.eof())
{
data="";
payroll_file >> data;
cout << setw(9) << data << endl;
}
payroll_file.close();
}
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 473

Open Modes
ifstream( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot );

ios::in The file is opened for input (default).


ios::nocreate If the file does not already exist, the function fails.
ios::binary Opens the file in binary mode (the default is text mode).
Note that the ios::nocreate flag is necessary if you intend to test for the file’s
existence (the usual case).

The file protection specification; defaults to the static integer filebuf::openprot that is
equivalent to filebuf::sh_compat. The possible nProt values are:

filebuf::sh_compat Compatibility share mode.


filebuf::sh_none Exclusive mode — no sharing.
filebuf::sh_read Read sharing allowed.
filebuf::sh_write Write sharing allowed.
To combine the filebuf::sh_read and filebuf::sh_write modes, use the logical OR (
|| ) operator.

(Extracted from MSDN Online)

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 474

Notes: 237
2006 C++ Course Handouts January 2006

Example of a Seed Read


void main()
{
//declare and initialize variable
short score = 0;
short numScores = 0; //counter
short totalScores = 0; //accumulator
float average = (float) 0.0;
//open input file
ifstream inFile;
inFile.open("scores.dat", ios::in | ios::nocreate);
//verify that open was successful
if (!inFile.fail()) //if open did not fail
{
//read test score
inFile >> score; // Seed Read
while (!inFile.eof())
{
//update counter and accumulator
numScores = numScores + 1;
totalScores = totalScores + score;
inFile >> score;
}
//close file
inFile.close();
//calculate and display average test score
average = (float) totalScores / (float) numScores;
cout << "Average test score: " << average << endl;
}
else //open failed
cout << "Error opening file." << endl;
} //end of main function

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 475

Character I/O

#include <fstream.h>
cin.get(char variable);
cout.put(char variable);
out_stream.put(char variable);
in_stream.get(char variable);
cin belongs to istream, NOT ifstream
cout belongs to ostream, NOT ofstream

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 476

Notes: 238
2006 C++ Course Handouts January 2006

Copy and Print a C++ Source Code File


#include <fstream>
#include <iostream>
#include <stdlib>
using namespace std;
char ch;
void main(void)
{
ifstream fin;
ofstream fout;

fin.open("c:/data/c_programs/cis162ab/cross_ref.c");
fout.open("c:/data/c_programs/cis162ab/new.c");
if (fin.fail() != 0)
{
cout << "File Open Failed with Error Code: ";
cout << fin.fail() << "\n";
cout << "Program Aborting...\n\n";
exit(1);
}

while (!fin.eof())
{
fin.get(ch);
fout.put(ch);
cout.put(ch);
} Code Verified 5/30/01
fin.close();
fout.close();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 477

The ignore() Function


fin.ignore(100, ‘\n’); Stop reading and discarding chars
from the keyboard after consuming the next 100 chars or after
consuming a newline char, whichever occurs first

fin.ignore(25, ‘#’); Stop reading and discarding chars


from the keyboard after consuming the next 25 chars or after
consuming a # char, whichever occurs first

cin.ignore(10, ‘$’); Stop reading and discarding chars


from the keyboard after consuming the next 10 chars or after
consuming a $ char, whichever occurs first

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 478

Notes: 239
2006 C++ Course Handouts January 2006

Example - Editing a File of Text


#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
const char TAB=9;
void add_plus_plus(ifstream& in_stream, ofstream& out_stream);
void main( )
{
ifstream fin;
ofstream fout;
fin.open("c:/data/cpp/cis162/Spring2003/demos/demoprob22.cpp");
if (fin.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("c:/data/cpp/cis162/Spring2003/demos/summaryfile.txt");
if (fout.fail( ))
{
cout << "Output file opening failed.\n";
exit(1);
}
add_plus_plus(fin, fout);
fin.close( );
fout.close( );
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 479

Example - Editing a File of Text


void add_plus_plus(ifstream& in_stream, ofstream& out_stream)
{
char ch;
int tabs=0;
int pounds=0;
int semicolons=0;

in_stream.get(ch); // seed read


while (! in_stream.eof( ))
{
if (ch == ';')
{
out_stream << ".";
semicolons++;
}
else
{
if (ch == '#')
pounds++;
if (ch == TAB)
tabs++;
out_stream << ch;
}
in_stream.get(ch);
} // end of while
cout << " Pound Signs:" << pounds << endl;
cout << " Semicolons:" << semicolons << endl;
cout << "Tab Characters:" << tabs << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 480

Notes: 240
2006 C++ Course Handouts January 2006

Basic Flow When Using Files

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 481

Formatting Output
fileout.setf(ios::fixed);
fileout.setf(ios::showpoint);
fileout.precision(4);

Sets the precision and attributes to be used on


subsequent I/O functions. More in Appendix of
Handout

setf attributes
ios::fixed // don’t use scientific notation
ios::scientific // use scientific notation
ios::showpoint // always show a decimal point
ios::showpos // show a plus on positive
ios::right // right justify
ios::left // left justify

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 482

Notes: 241
2006 C++ Course Handouts January 2006

I/O Manipulators

Placed after the << operator


dec
endl
fixedf
flush
hex
oct
right
scientific
setfill(ch)
setprecision(n)
setw(n)
showpoint
noshowpoint
shopos
noshowpos

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 483

Write Method

Using write()
Syntax: oblect.write(variable, length);

#include <iostream>
#include <string>
using namespace std;
Output
void main ()
{
One if by land
char One[] = "One if by land"; One if
One
int fullLength = strlen(One);
int length2 = strlen(One)/2;
int length3 = strlen(One)/4;

cout.write(One,fullLength) << "\n";


cout.write(One,length2) << "\n";
cout.write(One,length3) << "\n";
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 484

Notes: 242
2006 C++ Course Handouts January 2006

Random Access Files


#include <iostream>
seekg is Seek Get
#include <fstream>
using namespace std; seekp is seek Put
int main()
{
fstream file("letters.txt", ios::in);
char ch;

file.seekg(5L, ios::beg);
file.get(ch);
cout << "Byte 5 from beginning: " << ch << endl;
file.seekg(-10L, ios::end);
file.get(ch);
cout << "Byte 10 from end: " << ch << endl;
file.seekg(3L, ios::cur);
file.get(ch);
cout << "Byte 3 from current: " << ch << endl;
file.close();
return 0;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 485

Random Access Files (1 of 3)


#include <iostream>
#include <fstream>
using namespace std;
#include "reinterpret.h"

// Declare a structure for the record


struct Info
{
char name[51];
int age;
char address1[51];
char address2[51];
char phone[14];
};

// Function Prototypes
long byteNum(int);
void showRec(Info);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 486

Notes: 243
2006 C++ Course Handouts January 2006

Random Access Files (2 of 3)


void main()
{
fstream people;
Info person;

people.open("people.dat", ios::in | ios::binary);


if (!people)
{
cout << "Error opening file. Program aborting.\n";
return 0;
}
cout << "Here is record 1:\n";
people.seekg(byteNum(1), ios::beg);
people.read(addr(&person), sizeof(person));
showRec(person);
cout << "\nHere is record 0:\n";
people.seekg(byteNum(0), ios::beg);
people.read(addr(&person), sizeof(person));
showRec(person);
people.close();
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 487

Random Access Files (3 of 3)


long byteNum(int recNum)
{
return sizeof(Info) * recNum;
}

void showRec(Info record)


{
cout << "Name: ";
cout << record.name << endl;
cout << "Age: ";
cout << record.age << endl;
cout << "Address line 1: ";
cout << record.address1 << endl;
cout << "Address line 2: ";
cout << record.address2 << endl;
cout << "Phone: ";
cout << record.phone << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 488

Notes: 244
2006 C++ Course Handouts January 2006

sprintf() .. way cool


Same as printf except output is directed into a string
Syntax:
sprintf(str, ”formatting string”, variables);

Examples:
sprintf(title,”%15s %8s %4i\n”, header, date, page);
sprintf(line,”%8s %8s %4i %c”, acct, date, quan, status);

Great for converting numeric to string


sprintf(num,”%12.2f”, double_num);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 489

Conversion Specifiers for sprintf

%c character
%d signed decimal integer
%e,E floating point e-notation or E-notation
%f floating point decimal notation
%g,G use %f(F) or %e(E) whichever is shorter
%i signed decimal integer
%o unsigned octal integer
%p pointer
%s string
%u unsigned decimal integer
%x,X unsigned hex integer
%% percent sign

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 490

Notes: 245
2006 C++ Course Handouts January 2006

Conversion Specification Modifiers

Format: %xy
where x is a modifier or flag
and y is the specification

%7.2f uses 7 bytes with 2 bytes for decimal fraction


%h4i prints short values
%ld long values (long int or unsigned long int)
%lf designates long double floating point
%-10i left justified and use 10 bytes
%+7d show plus sign and use 7 bytes
% 6.2f signed values displayed with leading space.
%#8.0f makes decimal point print even if value is 0
%010d fill area with leading zeros

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 491

sprinf can be used to convert Binary to ASCII


#include <iostream>
#include <string>

using namespace std; Verified 10/29/2002


float cost;
char str[10];
int length1, length2;
1243.22
length of cost is 4
void main () length of str is 7
{
cost=1243.22;
sprintf(str,"%6.2f", cost);
cout << str << endl;;
length1=sizeof(cost);
length2=strlen(str);
cout << "length of cost is " << length1 << endl;
cout << "length of str is " << length2 << endl;
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 492

Notes: 246
2006 C++ Course Handouts January 2006

Strstream – Writes to Memory


#include <iostream>
#include <strstream>
#include <iomanip> Generated Output:
using namespace std; 1.0 4.0 9.0 16.0 25.0
int main()
{
float squares[5] = {1, 4, 9, 16, 25};

strstream outStr; //String stream object.

outStr << showpoint << fixed << setprecision(1);


outStr.clear(); // I added this to clear the buffer
outStr.flush();
for (int index = 0; index < 5; index++)
{
outStr << setw(10) << squares[index];
}

//Print the string on the screen.


cout << outStr.str();
return 0; Verified 11/22/2003
}

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 493

Review Questions
Name the two types of file I/O in C++?
The open statement is considered to be a _____ function.
ifstream is considered to be a _____________
We use ifstream and ofstream to instantiate a file _______?
What member function is used to determine if the previous I/O was
successful?
What member function is used to capture and report the end of a
file condition?
What must a programmer do to re-read the first line of a file?
What include directive do you need to process data files?
What happens to a data file when we open it for output?
Why would we want to close a file that was opened for input?
Why would we want to close a file that was opened for output?
What is a good use for the sprintf function?

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 494

Notes: 247
2006 C++ Course Handouts January 2006

Homework
1. Should have read Chapters 1 through 10 , 12 13 by now
2. Work on your term paper
3. Work on Homework Packets

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 495

Chapter 13 Summary

I/O Streams Summary

Stream I/O
Character I/O
fail()
good()
eof()
sprintf()
Manipulators
setf()

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 496

Notes: 248
2006 C++ Course Handouts January 2006

Additional C++ Topics

Advanced Topics

Bitwise Operators
Bit Fields
C-Style File I/O Operations
Recursion
Pointers
I/O Redirection

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 497

Interesting Facts
Most Computers, Intel, Motorola or anything else
use binary as the internal representation

There has been some experimentation at ASU with


Base 3 (1993 time frame)
n A.A. Rodriguiz - Professor in Electrical
Engineering Dept

Most PC’s, typically, use hexidecimal as the next


level of data representation

Some larger machine architectures use Octal

At one time there was a Hewlett Packard machine


that used base 5, or Radix 5
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 498

Notes: 249
2006 C++ Course Handouts January 2006

Boolean Operations

AND Operation
OR Operation
XOR Operation
One’s Complement Operation
Left Shift
Right Shift

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 499

Bitwise Operations

Key to success

AND means multiply


OR means add

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 500

Notes: 250
2006 C++ Course Handouts January 2006

Bitwise AND Operation

00101011 43
10101010 170
00101010 42 Remember to multiply

Why would we want to do this ?


Convert to upper or lower case

01001101 Upper case M 77


01101101 Lower case m 109

01101101 Lower case m 109


11011111 Mask of 223 223
01001101 Result is upper case M

Of course, we could have used toupper(‘m’);

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 501

Bitwise AND Operation


#include <iostream.h>
#include <iomanip.h>

unsigned val=109;
unsigned mask=223; // Bitwise AND Operation
unsigned newval;

main()
{

newval = val & mask;


cout << setw(4) << val << setw(4) << mask << setw(4) << newval
<< setw(4) << (char) val << setw(4) << (char) newval;
return(0);
}

109 223 77 m M

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 502

Notes: 251
2006 C++ Course Handouts January 2006

Bitwise OR Operation

00101011 43
10101010 170
10101011 171 Remember we’re adding, now

Why would we want to do this ?


Encoding / Decoding Algorithms
Communications Error Checking (CRC)
Manipulating TCP/IP packet addresses
Sub-net masks on Internet firewalls (198.200.78.41)
Display Graphics Manipulations
Master Bit Notation
File Allocation Tables on some machines

262,000 tracks, 1 bit for each track=32750 bytes


7168 bytes/track uses 5 tracks for MBT

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 503

Bitwise OR Operation
#include <iostream.h>
#include <iomanip.h>

unsigned val=43;
unsigned mask=170; // Bitwise OR Operation
unsigned newval;

main()
{

newval = val | mask;


cout << setw(4) << val << setw(4) << mask << setw(4) << newval;
return(0);
}

Prints:
43 170 171

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 504

Notes: 252
2006 C++ Course Handouts January 2006

Bitwise XOR Operation

Exclusive OR (one or the other but not both)

00101011 43
10101010 170
10000001 129 Remember we’re adding, Again

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 505

Bitwise XOR Operation


#include <iostream.h>
#include <iomanip.h>

unsigned val=43;
unsigned mask=170; // Bitwise XOR Operation
unsigned newval;

main()
{
newval = val ^ mask;
cout << setw(4) << val << setw(4) << mask << setw(4) << newval;
return(0);
}

Prints: 43 170 129

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 506

Notes: 253
2006 C++ Course Handouts January 2006

Complement Operation

Inverse function flips each bit (bitwise negation)


00101011 43
11010100 212

11111111 255
00000000 0

Why would we want to do this ?


Encoding / Decoding Algorithms
Communications Error Checking (CRC)
Manipulating TCP/IP packet addresses
Sub-net masks on Internet firewalls (198.200.78.41)
Display Graphics Manipulations

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 507

Shifting Operations

Basics of the right shift

01011100 92
00101110 46
00010111 23
00001011 11
00000101 5
00000010 2
00000001 1

Notice it is a divide by two operation

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 508

Notes: 254
2006 C++ Course Handouts January 2006

Shifting Operations

Basics of the left shift

01011100 92
10111000 184
01110000 112
11100000 224
11000000 192
10000000 128

Notice it is a multiply by two operation

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 509

Shifting Example
#include <iostream.h>
#include <iomanip.h>
unsigned val=92;
int i;

main()
Prints:
{
92
for (i=0; i<9; i++)
{ 184
cout << setw(8) << val << endl; 368
val = val << 1; 736
} 1472
return(0); 2944
} 5888
11776
23552
Prints:
92 184 368 736 46 23

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 510

Notes: 255
2006 C++ Course Handouts January 2006

C++ Pointers

#include <iostream>
#include <iomanip>
using namespace std;

int x;

void main(void)
{
x=6000;
cout << setw(8) << x << setw(18) << &x << endl;
}

Output:
Verified 11/27/2003
6000 00477748

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 511

C++ Pointers
#include <iostream>
using namespace std; Address of x: 00477738
double d1;
Address of iptr: 0047773C
double d2; Contents of iptr: 00477738
int x; Value of x: 100
int *iptr; Contents of dptr1: 00477750
double *dptr1; Contents of dptr2: 00477758
double *dptr2;

void main(void) Notice the length of the double is


{ obviously 8 bytes based on the
x = 100; difference in the addresses
iptr = &x;
dptr1 = &d1;
dptr2 = &d2; Verified 11/27/2003

cout << “ Address of x: " << &x << endl;


cout << “ Address of iptr: " << &iptr << endl;
cout << “ Contents of iptr: " << iptr << endl;
cout << " Value of x: " << *iptr << endl;
cout << "Contents of dptr1: " << dptr1 << endl;
cout << "Contents of dptr2: " << dptr2 << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 512

Notes: 256
2006 C++ Course Handouts January 2006

Register class
#include <stdio.h>
register x=0, var=0; // register class
int y=0, count=0; // signed integers

int main(void)
{
for (x=0; x<10000; x++) Register access 2 cycles
count++;
for (y=0; y<10000; y++) Memory access 12 cycles
count++;
. Each cycle is one tick of the
. clock.
return(0);
}

Notes: Uses very fast registers compared to memory

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 513

Register class

Register access 1 to 2 cycles


Memory access 12 to 20 cycles
10 to 12 times slower than register access
Disk access 5 milliseconds per I/O
2,000,000 times slower than register access

Each cycle is one tick of the clock.


.000000003 seconds per tick
1 / 400 MHz

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 514

Notes: 257
2006 C++ Course Handouts January 2006

Generated Internal Code

Typical increment structure

loop: mov ax,count ; get initial value


inc ax ; increment register
mov count,ax ; replace it
mov dx,y ; load y into dx
inc dx ; increment register
mov y,dx ; store it back
cmp dx,10000 ; test for exit
jle loop ; play it again, Sam

Some machines have memory increment instructions,


but, register operations are still faster than memory to
memory instructions.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 515

Generated Internal Code

Register class increment structure

clr ax ; clear ax register


clr dx ; clear dx register
loop: inc dx ; increment register
inc ax ; increment register
cmp ax,10000 ; test for exit
jle loop ; do it again

Six lines of code -- faster than the previous 8

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 516

Notes: 258
2006 C++ Course Handouts January 2006

volatile Type Qualifier

Means a variable can be altered by some external process


volatile int counter = 0;
volatile int memloc;

int main(void)
{
.
. Other C++ Code
.
}

Typically, a memory location.


Also called a common area or common bank.

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 517

volatile Type Qualifier

volatile int counter

Program A Program B Program C

counter++ counter++ counter++

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 518

Notes: 259
2006 C++ Course Handouts January 2006

Summary

Summary of Boolean Operations, Hex, Binary, Octal

Boolean Expressions
Enumeration Types
Bitwise Operators
Register Class
Volatile & Extern

3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 519

Notes: 260

Você também pode gostar