Download - CPP Presentation
2006 C++ Course Handouts January 2006
Notes: 1
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 1
C++ Programming and Computer Science
CIS162
CSC100
Version 17
2006
23/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
First Night RoadmapSocial AmenitiesAttendanceIntroductionsDiscuss SyllabusDiscuss Course ObjectivesMake Sure We Are Clear on AssignmentsWho Has Computer Access and C++ CompilersTalk a little About Computers and C++
2006 C++ Course Handouts January 2006
Notes: 2
33/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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.
43/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Course Objectives1. Explain the history of C++ and basic computer components2. Describe the software development process3. Use predefined data types to declare and manipulate variables and
arrays4. Use operators in arithmetic and Boolean expressions5. Design and develop structured/modular programs using various flow
control structures and functions6. Describe object-oriented concepts7. Design and develop programs using classes and object-oriented
programming techniques8. Process keyboard input and console output9. Debug simple and complex programming errors10. Use standard preprocessor commands11. Understand the concepts used in the construction of C++ programs,12. Understand and implement most C++ functions13. Understand basic structured programming concepts14. Understand encapsulation, inheritance, scope and overloading15. Improve your critical thinking skills16. Understand the relationship between high-level, low-level and
machine languages17. Understand bit-wise manipulation of data18. Understand data conversions from binary, decimal and hexidecimal
2006 C++ Course Handouts January 2006
Notes: 3
53/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
An Excellent TextStarting out with C++,
Alternate Version4th 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.
63/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Grading Policy
100% - 90% A89% - 80% B79% - 70% C69% - 60% DBelow 60 Ooops
Grading PolicyAssignments 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.
2006 C++ Course Handouts January 2006
Notes: 4
73/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Student DeliverablesAssignment or Activity PercentHomework 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”
83/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
How To Calculate Your GradeAssignment or Activity Percent Actual ExtendedMidterm Exam 24% x 90% = .2160Homework 32% x 94% = .3008Critical Thinking Paper 5% x 95% = .0475Final Celebration 24% x 80% = .1920
Quiz-1 6% x 100% = .0600Quiz-2 6% x 60% = .0360Attendance 3% x 100% = .0300
Total .8823 Extra Credit Paper 5% x 90% = .0450
Grand Total .9273 (92.73%)
Example-1
2006 C++ Course Handouts January 2006
Notes: 5
93/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
How To Calculate Your GradeAssignment or Activity Percent Actual ExtendedMidterm Exam 24% x 90% = .2160Homework 32% x 88% = .2816Critical Thinking Paper 5% x 95% = .0475Final Celebration 24% x 80% = .1920
Quiz-1 6% x 80% = .0480Quiz-2 6% x 60% = .0360Attendance 3% x 75% = .0225
Total .8436 Extra Credit Paper 5% x 90% = .0450
Grand Total .8886 (88.86%)
Example-2
103/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Course Road MapClass-1 January 20In 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
2006 C++ Course Handouts January 2006
Notes: 6
113/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Course Road Map
123/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
College Calendar
SPRING SEMESTER - 2006Sat Jan 14 Classes Begin
Mon Jan 16 Observance of M L King BirthdayMon Feb 20 Observance of Presidents' Day
Fri Mar 3 Last Day for Withdrawal without Instructor's SignatureMon-Sun Mar 13-19 Spring Break
Mon Apr 24 Last Day Student Initiated Withdrawal AcceptedSun May 7 Last Day of Regular Classes
Mon-Thu May 8-11 **Final ExamsFri May 12 Commencement
Fri May 12 Spring Semester EndsMon May 29 Observance of Memorial Day
2006 C++ Course Handouts January 2006
Notes: 7
133/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Class StructureStructure of the Class
Discussions Each Class Night Roughly 2 hours per night of discussion /dialog
C++ and Software EngineeringSoftware Development and MethodologiesComputer TechnologyEncryption & Decryption TechniquesCareers in IT, BusinessEthics in the Computer Industry
Lab Work Roughly 1 hour per night32 Programming ExercisesHome or the School Labs
Class and Group ActivitiesC++ Expert Panel DiscussionsStudent Teach Back AssignmentsIn-Class Group Assignments
143/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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%
2006 C++ Course Handouts January 2006
Notes: 8
153/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Critical Thinking Term Paper
Critical Thinking Term PaperFive pages, double spaced, cover page, references.
Topics to Choose FromImplementing C++ functions and templatesorAll About C++ Classes and Structures
163/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Grading Standards For Term Papers
Term PaperCover Page 5%
References 5%Grammar 5%Spelling 5%Length 5%Margins 5%Page Numbers, Dates, Headings 5%Content 65%
2006 C++ Course Handouts January 2006
Notes: 9
173/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Teaching Philosophy
I am here to teach, you're here to learnI believe if you apply yourself to the discussions and exercises you can learn this material, easily.I believe in respect for the studentI believe in respect for the technology
183/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
How We LearnWe will proceed through many different learning methods
LecturesDialogsDiscussionsPresentationsStudent Teach-BackGroup CollaborationWritingDebatesPractice by Doing C++ in ClassPractice by Doing C++ at HomeEmail ActivitiesResearching TopicsHave Some Fun, too
2006 C++ Course Handouts January 2006
Notes: 10
193/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Outcomes and AssessmentsStatement Regarding Outcomes and AssessmentThe 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.
203/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Students with Disabilities
Statement Regarding Students with DisabilitiesStudents 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
2006 C++ Course Handouts January 2006
Notes: 11
213/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
223/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Plagiarism
Statement Concerning PlagiarismPlagiarism 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."
2006 C++ Course Handouts January 2006
Notes: 12
233/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Instructor Contact Information
Jim Adams
Work: (480) 929-9803Email (Work): [email protected] (Home): [email protected] Page: www.softwaredynamix.com/javashop/index.php
Software Engineer 25+ yearsTeaching since 1996 (C++, Java, Statistics, VB, COBOL)Developed code using C, C++, FORTRAN, COBOL, Java, Assembler, VB, C#, PHP, PERLBS in Engineering, Mathematics MajorMBA Technology ManagementMS Systems and Software Engineering
Division Secretary: Carlene Weberg (480) 732-7043
243/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Web Page
URL is:www.softwaredynamix.com/javashop/index.php
Contains lots of C++ related informationSyllabus and Course ObjectivesOnline Midterm and Final ExamsSample C++ Code Homework ProblemsContact InformationPrevious Test Scores
2006 C++ Course Handouts January 2006
Notes: 13
253/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Now, I Need Some Information..
On the 3x5 cards, write:
1. Name2. Phone3. Email Address4. Where You Work5. Hobbies or Interests
263/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Syllabus Summary
Text BooksHomework & Lab TimeAttendanceClass StructureGradingC++ CompilersInstructor Contact InformationUpon 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++…
2006 C++ Course Handouts January 2006
Notes: 14
273/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 1
Introduction to C++, Computer Systems and Problem
SolvingComputer SystemsHardware, SoftwareCompilersGenerations of ComputersAlgorithmsSoftware Life CycleOrigins of C++Types of Programming ErrorsSample C++ ProgramsProblem Solving
283/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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?
2006 C++ Course Handouts January 2006
Notes: 15
293/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Computer Systems
Input Devices
Scanners, ModemsMIDI DevicesZip Drives, Jazz Drives, Tape DrivesDisk DrivesKeyboard
Output Devices
CRTModemsMIDI DevicesZip Drives, Jazz Drives, Tape DrivesDisk DrivesPrinters
CPU
Main Memory
RAM
These are all things you can touch—hardware types of things. They send data to the CPU and they take information from the CPU. Hence the phrase, Input, Process, Output, or IPO.
Software is used to control these devices. C++ is the language of choice in managing and controlling hardware devices.
303/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Computer Systems
Main Memory
Disk Secondary Storage
Input
Output
ALU
Bus
Primary Storage
CPUHardware Bus size determines C++ memory access size
Hardware
Registers
2006 C++ Course Handouts January 2006
Notes: 16
313/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Computer Memory Layout
E a c h b y t e h a s
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D
Relative AddressBase Address,
say, 8000
323/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Units of Measure
Binary 1 bit, either zero or oneBits Bunches of zeros & onesNibble 4 bits (1/2 byte)Bytes 8 bits (1 character)Words 16, 32 or 64 bits (Machine Dependent)Kilobytes KB 1024 bytesMegabytes MB 1 million bytesGigabytes GB 1 billion bytesTerabytes TB 1 trillion bytes
Milli, Micro, Nano, Pico .001, .000001, .000000001
2006 C++ Course Handouts January 2006
Notes: 17
333/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
History of C and C++
Ken Thompson and Dennis Ritchie in 1972Started out on UNIXBCPL or B language (Used for O/S’s)They were looking for a clever way to build systems software without using AssemblerToday, C is on every platform, imaginableC, C++, Visual C++, Advanced C
Who knows the difference between system software and application software?
A high-level programming language developed by BjarneStroustrup 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
343/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Where Is C++ Used?
Sequential, Linear ApplicationsEvent Driven ApplicationsSystem software
Operating systems, DOS, sorts, utilitiesAnalogous to heart and lungs
ToolsCompilers, Data Utilities, (Copies, Sorts, Finds, etc)
RoboticsPick & Place, Industrial Robotics
Game SoftwareEmbedded Systems (Who can give an example?)Communication Software
Netscape, Internet Explorer, Modem-based Software, Printer Drivers, Communications Drivers
Application softwareAccounts Payable, Payroll, Inventory, Sales Analysis, Marketing, etc
2006 C++ Course Handouts January 2006
Notes: 18
353/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 PortableCan 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
363/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
C++ is Programmer Oriented
Programmer orientedAccess to memory locationsBit manipulationsRobust set of operators (+, -, /, *, |, &&, etc)Character orientedNot very strict with respect to data types
Pascal is very strict, for exampleEasy to make mistakes, but, you can do most everything imaginableGood News: You can do anything with C++Bad News: You can do anything with C++
2006 C++ Course Handouts January 2006
Notes: 19
373/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Steps in Program Development
Questions to Think About1. 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?
383/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Steps in Program Development
Define objectivesPreliminary design (Flow Chart Perhaps)
Write the code (Implies some kind of editor)
Compile & linkRun the programTest and debugMaintain and modifyDocument
Today, we tend to use an iterative approach
Process
Decision
InputOutput
O nlineStorage
Tape
Off-PageConnect
or
D isplay
ManualOpera tion
Predefined Process
2006 C++ Course Handouts January 2006
Notes: 20
393/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Flowcharting
Open File
Start
Read a Byte
EOF
Close File
Print Byte
Stop
Yes
No
Entity Relationship DiagramsState Transition Diagrams
Flow Charts
403/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Developing a Solid Program
Break the program up into sections such as reading inputdisplaying outputprocessing 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()
2006 C++ Course Handouts January 2006
Notes: 21
413/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Systems Development Life Cycle
Preliminary Investigation
Systems Analysis
Systems Design
Systems Development
Implementation
Maintenance
423/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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.
2006 C++ Course Handouts January 2006
Notes: 22
433/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Problem Solving Technique
Break Down the Problem into its component parts
InputProcessingOutput
Very popular in programming and technologySometimes it’s helpful to start with the Output
Screen layout, report layout, etc
Desk checkingManual testing with sample dataQuality assurance (QA)Walk through
443/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Algorithms
Like a recipeSame as
DirectionsMethodsProcedures
An algorithm is a sequence of precise instructions that leads to a solutionWe’ll use the word “algorithm” a lot in this classSorting, searching, etcPayroll applications have many algorithms,
Bonus calculations, pay calculations, tax calculations
2006 C++ Course Handouts January 2006
Notes: 23
453/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 1 Summary
Introduction to Computer & Programming
Computer SystemsCompilersAlgorithmsSoftware Life CycleOrigins of C++Types of Programming ErrorsSample C++ Programs
Homework:1. Read Chapter 1 and 2 in the text
book2. Install C++ Compiler3. Type in some of the sample C++
programs in chapter 14. Start Critical Thinking Paper
463/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 2
Introduction to C++
VariablesAssignment StatementsDeclarationscout#include directivesEscape SequencesData TypesArithmetic OperatorsSimple Flow ControlProgramming Style
2006 C++ Course Handouts January 2006
Notes: 24
473/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
What is Binary?
Binary Numbering System00000001 100000010 200000011 300000100 400000101 500000110 600000111 700001000 800001001 900001010 1000001011 11
11111111 255
Look at the supplemental information in the last chapter of this handout..
483/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Mechanics of Binary?
Mechanics of Number Systems
Decimal Number System123410=1x103+2x102+3x101+4x100
Binary Number System10012=1x23 + 0x22 + 0x21 + 1x20
Any number to the 0th power is 1Any number to the 1st power is the number
itself
2006 C++ Course Handouts January 2006
Notes: 25
493/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
First Generation Programs--Binary
0100 1001490100 0101450011 1001390111 0010720011 11103E0000 0000001011 0011B31110 1111EF1010 1010AA0101 0101550000 11110F0001 11101E
0100 1001
4 9 in hex
01 001 001
1 1 1 in octal
each of which is 73
First there was actual binary. Then there was hex as a shorthand notation
Take 01001001 as an example
503/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Second Generation Programs--Assembler
Address Inst Mnemonic0110 0100 00100100 org $1000110 0101 00100010 mov 0, r10110 0110 00011100 add 10, r10110 0111 00111001 sto r1, counter0110 1000 00011111 ret0110 1001 00000000 counter
end
We wanted an easier way to get to machine code from some type of human readable code.
2006 C++ Course Handouts January 2006
Notes: 26
513/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Third Generation—FORTRAN,COBOL, C, etc
INTEGER FACTORIALDO N=1,12WRITE (6,*) N,' factorial is
',FACTORIAL (N)END DOEND
OPTIONS /RECURSIVEINTEGER FUNCTION FACTORIAL (N)
!! The Factorial of an integer N is N * N-1 *
N-2 ... * 1. ! passing N-1 to perform the calculation.
Note that ! each recursive call to FACTORIAL will get
its own ! copy of N.!! If N is 1 or less, the result is 1. (We
assume thatIF (N .GT. 1) THENFACTORIAL = FACTORIAL(N-1) * N
ELSEFACTORIAL = 1
END IF
RETURNEND
PROCEDURE DIVISION.
Begin.
DISPLAY "Enter student details using template below".
DISPLAY "Enter -ID,Surname,Initials,CourseCode,Gender"
DISPLAY "SSSSSSSNNNNNNNNIICCCCG".
ACCEPT StudentDetails.
ACCEPT CurrentDate FROM DATE YYYYMMDD.
ACCEPT DayOfYear FROM DAY YYYYDDD.
ACCEPT CurrentTime FROM TIME.
DISPLAY "Name is ", Initials SPACE Surname.
DISPLAY "Date is " CurrentDay SPACE CurrentMonth SPACE CurrentYear.
DISPLAY "Today is day " YearDay " of the year".
DISPLAY "The time is " CurrentHour ":" CurrentMinute.
STOP RUN.
523/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Fourth Generation ProgramsC++, Java, SQL, VB
#include <iostream>using namespace std;
main(){
cout << “This is a simple C++ Program “ << endl;
}
2006 C++ Course Handouts January 2006
Notes: 27
533/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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";
}
543/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Basic C++ Construction
#include <iostream>using namespace std;
int main(){variable declarations
C++ statements
return(0);}
Include directive
Main Body
Return statement
2006 C++ Course Handouts January 2006
Notes: 28
553/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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..”);
563/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Code Blocks & White Space
Code BlocksBraces
{Marks the begin and end of a block of code
}
White Space
2006 C++ Course Handouts January 2006
Notes: 29
573/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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";
}
583/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Syntax v. Semantic Errors
Syntax or Compile Time errors are caused by uncertain coding that the compiler cannot understand. Sometimes called Semanticerrors.
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 takenint x=10;cout << “X cubed is:“ << x*x;
if (sales_amount > 1.00) then sales_tax = 0
2006 C++ Course Handouts January 2006
Notes: 30
593/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
As you might guess,Compilers are extremely complex pieces of softwareCompilers must parse each line of source code
Called a translation unitdetect syntax errorsgenerate variable space in the symbol tablegenerate assembler code equivalent to the C codeassemble the assembler code into object codelinks object code into an executable file .EXE
Compilers
603/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Source, Object and Executable
C++ is the Source CodeCompiler converts to an Object moduleThe Linker converts the object module to an Executable
C++ Source Compile Object Linker .EXE
User types in C++ Source Code
2006 C++ Course Handouts January 2006
Notes: 31
613/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Compile and Build Process1. Look at the Problem you need to solve2. Design with paper and pencil the input, process and
output3. Open the IDE (MS or Borland for example)4. Type in your C++ code5. Compile it (F7 on MS)6. Fix Errors7. Run the Program
Compiler creates several files1. C++ Source (You type this in)2. .exe file3. .dsp files4. .ncb files5. .prj files6. .opt files 7. .plg files
623/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
How to Print Results
1. Click the upper left corner2. Choose “Edit” then “Mark”3. Select the text you want to print4. Click the upper left corner, again5. Select “Edit” and then “Copy”6. Copy and paste to MS Word or
back into the compiled source code
1. Click the upper left corner2. Choose “Edit” then “Mark”3. Select the text you want to print4. Click the upper left corner, again5. Select “Edit” and then “Copy”6. Copy and paste to MS Word or back into the compiled source code
2006 C++ Course Handouts January 2006
Notes: 32
633/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Questions1. Who can discuss the difference
between a keyword and a variable?2. What is a C++ Comment?
C++ Keywords and Variables
643/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
1. asm2. auto3. break4. bool5. case6. catch7. char8. class9. const10. continue11. default12. delete13. do14. double15. else16. enum17. extern18. explicit19. false20. float
21. for 22. friend23. goto24. if25. inline26. int27. long28. mutable29. namespace30. new31. operator32. private33. protected34. public35. register36. return37. short38. signed39. sizeof40. static
C++ Keywords41.struct42.switch43.template44.this45.throw46.true47.try48.typedef49.typeid50.typename51.union52.unsigned53.using54.virtual55.void56.volatile57.while
2006 C++ Course Handouts January 2006
Notes: 33
653/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Tokens
Smallest source-code element recognized by the compiler
keywordsidentifiersconstantsstringsoperatorspunctuator
int counter=0; counter++;
663/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 34
673/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Five Type of Statements in C++
Null Statements (Comments)
Declaration StatementsAssignment StatementsControl StatementsFunctions
683/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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);
2006 C++ Course Handouts January 2006
Notes: 35
693/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 ;// ;----------------------------------------------------------;
703/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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.
2006 C++ Course Handouts January 2006
Notes: 36
713/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
What Is a VariableA Variable is place in computer memory where we store information used in our programs.
Each data variable has three componentsIts Name,
Its Value,
Its Type
723/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Variable DeclarationAll variables must be declared before they are used
SyntaxType_Name Variable_Name_1, Variable_Name_2, Variable_Name_n;Type_Name Variable_Name=initial_value;Type_Name Variable_Name(initial value);
Examplesint 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;
2006 C++ Course Handouts January 2006
Notes: 37
733/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Variable Declaration
Variable Name Choiceup to 31 characters (ANSI Standard)lowercase & uppercaseunderscore charactervariables must begin with a letter or the underscore character
Microsoft allows 247 characters
743/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Variable Declaration
Each variable takes a certain amount of memory space depending on the type of compiler
int count; // 2 bytes internallyint i;
char ch=‘A’; // 1 byte internallychar status;
float cost; // 4 bytes internallyfloat vector;
double nations_debt; // 8 bytes internallydouble sum;
2006 C++ Course Handouts January 2006
Notes: 38
753/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Variable Declaration
Names you supply for variable types of informationWe Declare Variables More Examples:
int result;int count;
Variables (identifiers) are case sensitiveint Adder;int adder; // these are different
763/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Meaningful Variable Names
Use Meaningful Names
x = y * z;
distance = speed * time;tax = cost * tax_rate;Voltage = Amperes * Resistance;
2006 C++ Course Handouts January 2006
Notes: 39
773/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Meaningful Variable NamesDeclaring a VariableStay 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.
783/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Valid Variable Declarations
Valid Variable Namesdepositend_balwithdrawalcontinue_processResultFieldResultAnnualSalaryCostOfGoodsSoldSelling_Pricequantity_on_hand
2006 C++ Course Handouts January 2006
Notes: 40
793/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Invalid Variable Declarations
Invalid Variable Names2002DepositAmountend balwithdrawal.amtcontinuecharcoutintResult-Field1selling_price$cost
803/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Data Types
Character Data Typeschar stores a single characterstring stores a series of characters
Integral Data Typeslong stores large integersint -3, -2, -1, 0, 1, 2, 3, 4, 5, etcshort
Fractional Data Typesfloat numbers like 3.14159double numbers like 3.141598658934569876542301
Logical Data Typesbool true or false
2006 C++ Course Handouts January 2006
Notes: 41
813/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Data Types
Type Specifiers
int 16 bitslong 32 bitsshort 8 bitschar 8 bitsfloat 32 bitsdouble 64 bitsbool 8 bitsstring N/A
Type Modifiers
unsignedsigned
823/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Variable Data TypesType Size Valuesint 2 bytes -32,768 to 32,767unsigned int 2 bytes 0 to 65,535unsigned short int 1 byte 0 to 255short int 1 byte -127 to 127unsigned long int 4 bytes 0 to 4,294,967,295long int 4 bytes -2,147,483,648 to 2,147,483,647char 1 byte 256 character valuesfloat 4 bytes -3.4e-38 to +3,4e38double 8 bytes -1.7e-308 to +1.7e308bool 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.
2006 C++ Course Handouts January 2006
Notes: 42
833/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Integer Data Typesshort 0111 1111unsigned short 1111 1111int 0111 1111 1111 1111 unsigned int 1111 1111 1111 1111long 0111 1111 1111 1111 1111 1111 1111 1111unsigned long 1111 1111 1111 1111 1111 1111 1111 1111
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.
Sign Bit
843/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Size of an IntegerSize of IntegersOn 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.
2006 C++ Course Handouts January 2006
Notes: 43
853/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Integer Use Example#include <iostream>using namespace std;
void main(){
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";
}
Our checking balance is -2500 dollarsWe drove 4276 milesWe flew 186650 days to get to Saturn
863/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Overflow and UnderflowWhat happens when a numeric variable reaches maximum /
minimum values for a given data type
Integer with 32767 and 1 is added gives -32768because 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
2006 C++ Course Handouts January 2006
Notes: 44
873/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Break
883/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
char and string Data Typeschar 0000 0000 through 1111 1111string 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.”;
2006 C++ Course Handouts January 2006
Notes: 45
893/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Using Character Variables#include <iostream>using namespace std;
void main(void){
char letter;
letter=65;cout << letter << endl;letter=66;cout << letter << endl;letter=90;cout << letter << endl << endl;
letter='A';cout << letter << endl;letter='B';cout << letter << endl;letter='Z';cout << letter << endl;
}
Generated OutputABZ
ABZ
Code Verified 03/19/2003
A = 01000001
B = 01000010
903/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Variable Declaration
String Data Typestring myName;string yourName;string bookTitle;string Inventory_Item_Description;
Same aschar myName[30];char yourName[30];char bookTitle[45];char Inventory_Item_Description[60];
An Array of Characters
2006 C++ Course Handouts January 2006
Notes: 46
913/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Using String Variables#include <iostream>#include <string>using namespace std;
void main(){
string myName;string yourName;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;
}
Generated OutputAda LovelaceSally RideAda LovelaceSally Ride
Code Verified 04/29/2003
923/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Floating Point Data Typesfloat 4 bytesdouble 8 byteslong 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-1987generalizes 754 to cover decimal arithmetic as well as binary.bits 0-22 are fraction (mantissa)bits 23-30 are the exponentbit 31 is the sign bit
http://www.nuvisionmiami.com/books/asm/workbook/floating_tut.htm
2006 C++ Course Handouts January 2006
Notes: 47
933/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Floating Point Data Types
float 4 bytesdouble 8 byteslong double 8 bytes. Some use 10 or 16 bytes
float Range is -1.2e-38 to 3.4e38double Range is -2.2e-308 to 1.8e308
943/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Boolean Variable Declaration
Boolean Data Typebool 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);
2006 C++ Course Handouts January 2006
Notes: 48
953/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Boolean Variable Declaration#include <iostream>using namespace std;
void main(){
bool are_we_finished;
are_we_finished = false;cout << are_we_finished << "\n\n";
are_we_finished = true;cout << are_we_finished << "\n\n";
}
Generated Output
0
1
963/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
2006 C++ Course Handouts January 2006
Notes: 49
973/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Equivalents
Type Specifier Same Assigned int int or signedunsigned int unsignedsigned char charunsigned char no equivalentshort int short or signed shortsigned long int long or signed long
983/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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];
2006 C++ Course Handouts January 2006
Notes: 50
993/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;
1003/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 51
1013/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
ASCII v. Numeric
1023/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
2006 C++ Course Handouts January 2006
Notes: 52
1033/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Assignment Statements
Variable Initialization is Important in C++
Simple Examples:int x = 1;int count = 0;char ch = ' '; float cost = 0.0;double mass(0.0);
int main(){
x = 1;count = 0;mass = 0.0;cost = 0.0;ch = ' ';
}
Initialized at compile time
Initialized at run time
1043/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Assignment Statements
Multiple AssignmentsAn 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
2006 C++ Course Handouts January 2006
Notes: 53
1053/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The Beginning of Every C++ Program
#include <iostream>using namespace std;
Or
#include <iostream.h>
1063/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The cout Object
cout (character out)
Syntaxcout << variable-1 << variable-2 << text-1 << text-2;
Examplesint input_number=1000;cout << “Enter a number less than 100”;cout << “Number entered is ” << input_number << endl;cout << “Press Enter \n”;
2006 C++ Course Handouts January 2006
Notes: 54
1073/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The cout Object
Examplescout << “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;
1083/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
2006 C++ Course Handouts January 2006
Notes: 55
1093/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
More Detailed Escape Sequences
1103/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
#define -- preprocessor command
#define
preprocessor commandused for defining constants
Examples:#define PI 3.14159#define GRAVITY 32.2#define LF 10#define CR 13
2006 C++ Course Handouts January 2006
Notes: 56
1113/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
#define -- preprocessor command#include <iostream>using namespace std;#define PI 3.14159#define MAX 5
float diameter=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;}
Generated OutputCircumference is 32.9867Where Pi is 3.14159 and diameter is 10.5
1123/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
#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;
programbegin
display "Enter your age:";read_screen age;
end
Can actually define your own language
2006 C++ Course Handouts January 2006
Notes: 57
1133/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
1143/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 2 Summary
Introduction to C++
VariablesAssignment StatementDeclarationscoutEscape SequencesFormatting NumbersData TypesVarious OperatorsProgramming Style
2006 C++ Course Handouts January 2006
Notes: 58
1153/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 3
C++ Console Interaction
CinI/O ManipulatorsPrinting Hex and OctalOperatorsExpressions
1163/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
cin Object
cin (character in)
Syntaxcin >> variable-1 >> variable-2 >>. . . ;
Examplescin >> number1;cin >> mass_of_sun >> distance_from_earth;
2006 C++ Course Handouts January 2006
Notes: 59
1173/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
cin Object#include <iostream>using namespace std;
void main(){
int whole;float fraction;char letter;
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
Enter an integer, a float and a character: 1234 1234.456 B
Whole Number is:1234Fractional Number is:1234.46
Letter Entered is: B
1183/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Inputting a String (using char)// Also known as C-Strings#include <iostream>#include <string>using namespace std;
void main(){
char fullname[50];
cout << "Enter your full name: ";cin.getline(fullname, 50);
cout << fullname << endl;}
Enter your full name: Samuel F. B. MorseSamuel F. B. Morse
Member Function
cout and cinare Objects
2006 C++ Course Handouts January 2006
Notes: 60
1193/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);
cout << st << endl;}
Enter your full name: Samuel F. B. Morse
Samuel F. B. Morse
cin object
1203/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 operationsiomanip -- contains information useful for performing formatted I/O with parameterized stream manipulatorsfstream -- contains information for performing file I/O operationsstrstream -- contains information for performing in-memory I/O operations (i.e., into or from strings in memory)
2006 C++ Course Handouts January 2006
Notes: 61
1213/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
I/O Manipulatorscout.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 attributesios::fixed // don’t use scientific notationios::scientific // use scientific notationios::showpoint // always show a decimal pointios::noshowpoint // do not show a decimal pointios::showpos // show a plus on positiveios::noshowpos // show a plus on positiveios::right // right justifyios::left // left justify
1223/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Classes for Stream I/O in C++
ios is the base class.istream and ostream inherited from iosifstream 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
2006 C++ Course Handouts January 2006
Notes: 62
1233/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
1243/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
I/O Manipulator SummaryThere 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 justificationleft force left justificationfixed Fixed pointshowpoint Show the decimal pointflush 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 pBoolalpha Use strings true and falsenoboolalpha Use numeric 0 and 1 for booleanuppercasenouppercaseskipws Skip white space on inputnoskipws Don’t skip white space on input
2006 C++ Course Handouts January 2006
Notes: 63
1253/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
I/O Manipulator Example#include <iostream>using namespace std;
void main () {cout.setf ( ios_base::hex, ios_base::basefield ); // set hex as the basefieldcout.setf ( ios_base::showbase ); // activate showbasecout << 700 << endl;cout << 255 << endl;
cout.unsetf ( ios_base::hex ); // deactivate hexcout.setf ( ios_base::oct ); // activate octalcout << 700 << endl;cout << 255 << endl;
cout.unsetf ( ios_base::oct ); // deactivate hexcout.unsetf ( ios_base::showbase ); // deactivate showbasecout << 700 << endl;cout << 255 << endl;
}
Output0x2bc0xff
012740377
700255
Code tested 10/28/2002
1263/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
setprecision() Example#include <iostream>#include <iomanip>using namespace std;
void main(){
double cost=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;
}
1234.1234001234.123401234.12341234.1231234.121234.11234
2006 C++ Course Handouts January 2006
Notes: 64
1273/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
I/O Manipulator setw() Example
#include <iostream>#include <iomanip>using namespace std;
void main(){
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;
}
1.121.121.12
1.121.12
1.121.12
1283/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Using the IO Manipulators#include <iostream>#include <iomanip>using namespace std;
void main () {cout << setfill('0');cout << setw(5) << 700 << endl;cout << setw(5) << 255 << endl;
// print the numbers in hexidecimal formatcout << setw(5) << hex << 700 << endl;cout << setw(5) << hex << 255 << endl;
// print the numbers in octal formatcout << setw(5) << oct << 700 << endl;cout << setw(5) << oct << 255 << endl;
}
Output0070000255002bc000ff0127400377
Code tested 05/12/2003
2006 C++ Course Handouts January 2006
Notes: 65
1293/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Printing HEX & Octal
#include <iostream>#include <iomanip>using namespace std;
// Start of main logic sectionvoid 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;}
[***192]
[****c0]
[***300]
[***192]
3.1416
Output
Validated 7/13/2001
1303/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Let’s See What We Know!#include <iostream>#include <iomanip>using namespace std;
void main(){
double x;double y;double value;
// Get The User Inputcout << "Enter a number:";cin >> x;cout << "Enter another number:";cin >> y;value = (x * y) + x;
// Output Section Onecout << "Values Entered: "
<< fixed << setprecision(4) << setw(11)<< x << setw(11)<< y << endl;
cout << "Final Value: " << value << endl;}
Enter a number:123.33Enter another number:432.44Values Entered: 123.3300 432.4400Final Value: 53456.1552
Generated Output
Code Verified 05/03/2003
2006 C++ Course Handouts January 2006
Notes: 66
1313/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
sizeof() Operatorsizeof() operator
Used to obtain the size of any particular data typeExamples:
#include <iostream>using namespace std;
void main(){
int s;char ch;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;
}
Size of an Integer is: 2Size of a Long is: 4
Size of a Short is: 1Size of a Float is: 4
Size of a Double is: 8Size of a char is: 1
1323/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Operator Precedence
( ) Parentheses- + ++ -- Unary Operators* / % Multiply, Divide, Modulo+ - Plus, Minus< > <= >= Greater-Than, Less-Than== != Equal to, Not Equal to&& And|| Or= Set
2006 C++ Course Handouts January 2006
Notes: 67
1333/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Operators & Precedence
Plus, Minus, Multiply, Dividex = 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 Cautionbutter = 25.0 + 60.0 * n / scale;
1343/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Mathematical Expressions
Y = 3X2
Y = (3 * X) / 2;Y = (X / 2) * 3;Y = (3 / 2) * X;
2006 C++ Course Handouts January 2006
Notes: 68
1353/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Exponents in C++
y = 9x3+25y = (9 * pow(x,3)) + 25;
y = (9x3)5
y = pow((9 * pow(x,3)),5);
Exponent Functiony=pow(n, q); // n raised to the power of q
1363/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 69
1373/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Sine Function in C++
#include <iostream>#include <cmath>using namespace std;#define PI 3.14159
void main(){
double y, x;// 57.3248 degrees per radiany=sin(PI/2); // 90 degreescout << y << endl;y=sin(PI/4); // 45 degreescout << y << endl;y=sin(PI/2); // 90 degreescout << y << endl;y=sin(PI/3); // ?cout << y << endl;y=sin(0.5244); // 30 degreescout << y << endl;
}
10.70710610.8660250.500694
All trig functions in C++ assume radian measure
1383/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
strlen() Function
strlen() operatorUsed to obtain the size of a string’s contents
#include <iostream>using namespace std;
void main(){
int len;char myName[30];
strcpy(myName, "Santa Claus");len=strlen(myName);cout << myName << endl;cout << " Content Length:" << len << endl;cout << "String Capacity:" << sizeof(myName) << endl;
}
Santa ClausContent Length:11
String Capacity:30
2006 C++ Course Handouts January 2006
Notes: 70
1393/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Symbolic Constants
Used to guarantee integrity of a variable READ ONLY VariableCalled 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; // OkayPI = 3.2; // Not gonna happen
}
1403/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Literal Constants
Floating PointIntegerCharacter
A number, character or string that can be used as a value in a program.
2006 C++ Course Handouts January 2006
Notes: 71
1413/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Floating Point Constants
15.75 // 15.751.575E1 // 15.751575E-2 // 15.75-2.5e-3 // -0.002525e-4 // 0.0025
All floating point constants are stored as double precision unless otherwise stated.
110.21F floating point110.21D double
1423/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Integer Constants
10L Long Constant79L Long Integer Constant776745UL Long Unsigned778866LU Long Unsigned12345 Typical Integer Constant
2006 C++ Course Handouts January 2006
Notes: 72
1433/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Numeric ConstantsInteger constants can be decimal, octal or hexidecimal.
(base 10, 8 & 16)// Decimal Constants (Base 10)1013232179
// Octal Constants (Base 8)0120204076663
// Hexidecimal Constants (Base 16) Hex for short0xa or 0XA0x840x7db3
1443/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Character ConstantsUsed 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;
2006 C++ Course Handouts January 2006
Notes: 73
1453/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Operators= Assignment < less than<= less than or equal== equal to> greater than>= greater than or equal!= NOT equal to~ Compliment| Boolean Or& Boolean And ^ Exclusive Or>> Shift right<< Shift Left&& Logical And|| Logical Or! Not Operator
++ Auto Increment-- Auto Decrement+= Increment-= Subtract*= Multiply/= Divide%= Modulo% Modulo+ Add- Subtract* Multiply/ Division. Dot Operator:: Scope Resolution
1463/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Incrementing A VariableThe 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;
Incrementx=x+1; // Traditionalx+=1; // shorthand for x=x+1x++; // postfix mode, same as x=x+1++x; // prefix mode, same as x=x+1
2006 C++ Course Handouts January 2006
Notes: 74
1473/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Decrementing a VariableThe 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;
Decrementx=x-1; // Traditionalx-=1; // shorthand for x=x-1x--; // postfix mode, same as x=x-1--x; // prefix mode, same as x=x-1
1483/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Incrementing and Decrementing
Say we have,int x = 10;
Incrementx=x+5; // Traditionalx+=5; // shorthand for x=x+5
Decrementx=x-5; // Traditionalx-=5; // shorthand for x=x-5
2006 C++ Course Handouts January 2006
Notes: 75
1493/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Postfix / Prefix Example#include <iostream>using namespace std;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;}
Code Verified 6/21/2001
Result using postfix notation:4 3
Result using prefix notation: 6 3
1503/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
2006 C++ Course Handouts January 2006
Notes: 76
1513/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Type CastingSometimes 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 tofloat before performing the division.// Older C-style of type castingint sum, n;float average;average = (float) sum / n;
// C++ Style of type castingfloat average;average = float (sum) / n;
1523/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Type CastingThe 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 2because 1.6 converts to integer 1and 1.7 converts to integer 1Conversion is done before the addition operation
2006 C++ Course Handouts January 2006
Notes: 77
1533/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Character Constants & Initialization
char x;int main(){x='A';cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;cout << x++ << " " << (int) x << endl;}
A 65B 66C 67D 68E 69F 70G 71H 72I 73J 74
Output…Typecast Operator
1543/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Integer Division, Negating, Modulus
Dividing Integersint 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 -100z = -x; // set z to +100
Modulus Arithmeticint 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
2006 C++ Course Handouts January 2006
Notes: 78
1553/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Modulus OperatorModulus 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 operatorint nCentury;
if ((nCenturyYear % 4) == 0) {LeapYearFunction();
}
1563/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Modulus Division Example#include <iostream>using namespace std;
int main( ){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;}
}
Code Verified 09/19/2001
Large loop with a display every 10,000
2006 C++ Course Handouts January 2006
Notes: 79
1573/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Review Questions for Chapter 31. 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 typecasting4. 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?
1583/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 and 2 by now2. Read Chapter 3 for next week3. Work on your term paper4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 4 on page 161 of the text. (Chapter 3)
2006 C++ Course Handouts January 2006
Notes: 80
1593/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 3 Summary
Introduction to C++
VariablesAssignment StatementDeclarationscinEscape SequencesFormatting NumbersData TypesVarious OperatorsProgramming Style
1603/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 4
Making Decisions (Selection Structures)
If StatementIf -- ElseSwitch StatementLogical OperatorsExpressionsEnumerated Types
2006 C++ Course Handouts January 2006
Notes: 81
1613/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Insight
Computer Science states that a good language must be able to:
1. Execute a sequence of statements2. Repeat statements until some condition is met3. Test and branch between alternative statements
1623/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Logical Operators
Logical Operators&& And|| Or! NotProduces one of two values, TRUE or FALSE== !=<<=>>= Operate on pairs of built in types
2006 C++ Course Handouts January 2006
Notes: 82
1633/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Expression Examples
Code Fragment Examples
if (x < 100)if (x > 0)if (count <= 50)if (count >= 1000)if (ch != ‘Z’)if (status == 1)
1643/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
If Statement Syntax
Syntaxif (expression)
C++ statement
if (expression){C++ statementsC++ statements
}
2006 C++ Course Handouts January 2006
Notes: 83
1653/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
if statementExample
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
1663/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
2006 C++ Course Handouts January 2006
Notes: 84
1673/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
If - else
A Third Example Showing if -- elseif (remainder == 0)
cout << num2 << " is a factor of " << num1 << endl;else
cout << num2 << " is not a factor of " << num1 << endl;
1683/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
If Logic is tricky, sometimes …#include <iostream>using namespace std;
int main(){
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)grade = 'F';
if (testScore < 70)grade = 'D';
if (testScore < 80)grade = 'C';
if (testScore < 90)grade = 'B';
if (testScore <= 100)grade = 'A';
cout << "Your grade is " << grade << ".\n";}
Enter your test score and I will tell youthe letter grade you earned: 44Your grade is A.
The order of the logical comparisons is important
Verified 11/23/2003
2006 C++ Course Handouts January 2006
Notes: 85
1693/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
If Logic is tricky, sometimes …#include <iostream>using namespace std;
int main(){
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)grade = 'A';
if (testScore < 90)grade = 'B';
if (testScore < 80)grade = 'C';
if (testScore < 70)grade = 'D';
if (testScore < 60)grade = 'F';
cout << "Your grade is " << grade << ".\n";}
Enter your test score and I will tell youthe letter grade you earned: 44Your grade is F.
The order of the logical comparisons is important
Verified 11/23/2003
1703/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
else if construct #include <iostream>using namespace std;
int main(){
int testScore;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)grade = 'D';
else if (testScore < 80)grade = 'C';
else if (testScore < 90)grade = 'B';
else if (testScore <= 100)grade = 'A';
elsegoodScore = false;
if (goodScore)cout << "Your grade is " << grade << ".\n";
elsecout << testScore << " is an invalid score.\n";
}
Verified 11/23/2003
Or, we can use the else-if construct
Enter your numeric test score and I will tell you the letter grade you earned: 44Your grade is F.
2006 C++ Course Handouts January 2006
Notes: 86
1713/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
1723/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
}}
2006 C++ Course Handouts January 2006
Notes: 87
1733/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Nested if statementsvoid 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";}
1743/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Nested if statementsif (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);
elsetax = MARRIED_BASE3 + RATE3 * (income - MARRIED_CUTOFF2);
}
2006 C++ Course Handouts January 2006
Notes: 88
1753/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Logical Operators (or / and)
Example Showing && and ||And operator is &&Or operator is ||
And operatorif (income > 100000 && dependents == 0)
tax_amount = income * 0.33;
Or operatorif (income > 200000 || itemized_deductions > 50000)
call_an_audit = true;
1763/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 false8>7 is true
We have, (false && true)
False AND True will evaluate to False when using &&
2006 C++ Course Handouts January 2006
Notes: 89
1773/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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";
}}
1783/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Logical Or Condition
if ((year == 2000) && (month == 2) && (day == 29)){// Do some leap year stuff..}
if (year == 2000)if (month == 2)
if (day == 29)process_leap_year();
Lazy Evaluation of Boolean OperatorsBoolean Expressions are interpreted left to rightIn an OR condition, scanning stops once a true value is foundIn an AND condition, scanning stops once a false value is found
Which one is faster ?
2006 C++ Course Handouts January 2006
Notes: 90
1793/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Logical Or Conditionvoid 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‘ || 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";}
Making a previous example, better
1803/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The “OR” Operator
ExampleSay we have the following expression and y=8
((y<3) || (y>7))
So, 8<3 is false8>7 is true
We have, (false || true)
False OR True will evaluate to true when using ||
2006 C++ Course Handouts January 2006
Notes: 91
1813/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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";
}}
1823/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Some RulesAND ConditionExp-1 Exp-2 Exp1 && Exp2True True TrueTrue False FalseFalse True FalseFalse False False
OR Condition Exp-1 Exp-2 Exp1 || Exp2True True TrueTrue False TrueFalse True TrueFalse False False
2006 C++ Course Handouts January 2006
Notes: 92
1833/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Some RulesAND Condition (Multiply)Exp-1 Exp-2 Exp1 && Exp21 1 11 0 00 1 00 0 0
OR Condition (Add)Exp-1 Exp-2 Exp1 || Exp21 1 11 0 10 1 10 0 0Think of True as 1 and False as 0
1843/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Technical Notes
Logical ANDif ( (x == 5) && (y == 5) )if ( x == 5 && y == 5 )
Logical ORif ( (x == 5) || (y == 5) )if ( x == 5 || y == 5 )
Logical NOTThese are the sameif ( !(x == 5) )if (x != 5)
2006 C++ Course Handouts January 2006
Notes: 93
1853/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);
1863/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 94
1873/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;
1883/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Example of TRUE/FALSEint 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;
}
2006 C++ Course Handouts January 2006
Notes: 95
1893/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Not Operator
NOT Operation
Exp !Exp1 00 1
Think of True as 1 and False as 0
1903/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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";}
2006 C++ Course Handouts January 2006
Notes: 96
1913/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
De Morgan’s LawWhat if..if (amount > 0 && amount < 1000) …
Now let’s tryif (!(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.
1923/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
De Morgan’s LawLet’s prove it:
a b a+b !(a+b) !a !b a × b0 0 0 1 1 1 10 1 1 0 1 0 01 0 1 0 0 1 01 1 1 0 0 0 0
How cool is that?
2006 C++ Course Handouts January 2006
Notes: 97
1933/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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)
1943/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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”;
2006 C++ Course Handouts January 2006
Notes: 98
1953/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Common Problem
What output will be produced by the following code snippet?
w = 1;if (w = 2)cout << “w equals 2”;
1963/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 99
1973/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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”;
1983/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 100
1993/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Switch statementint 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 executedCan only be applied to integer and character data typesTest cases can only be constantsA very common error is to omit the breakstatement
2003/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Switch statement#include <iostream>using namespace std;
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;
}
Code Verified 09/20/2001
2006 C++ Course Handouts January 2006
Notes: 101
2013/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Switch Statement#include <iostream>using namespace std;
int main( ){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;
}}
Code Verified 09/19/2001
2023/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Code Blocks
if (day == 29)if (month == 2)
if (year == 2000){total_balance = 0.0;inventory_quantity = 100;cout << day << month << year;}
2006 C++ Course Handouts January 2006
Notes: 102
2033/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
2043/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
goto statement
Example of goto statementint x;
int main(void){
x = 0; start:cout << “Value of x is “ << x << endl;x++;if (x < 100)
goto start;}
2006 C++ Course Handouts January 2006
Notes: 103
2053/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The Conditional Operator
Syntax: expression ? Expression : expressiona = x > 100 ? 0 : 1;
Is the same asif (x > 100)a = 0;
elsea = 1;
2063/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The Conditional Operator
Syntax: expression ? Expression : expressionscore = 90;cout << "Your Grade is " << (score<60 ? "Fail“ : "Passing");
Is the same asif (score < 60)
cout << "Your Grade is Failing;else
cout << "Your Grade is Passing;
2006 C++ Course Handouts January 2006
Notes: 104
2073/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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; // Conditionaloperatorcharges = payRate * hours;
cout << fixed << showpoint << setprecision(2);cout << "The charges are $" << charges << endl;return 0;
}
2083/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Enumerated Types
enum Roster {Tom, Jim, Sharon, George, Carolyn, Bob};
Creates a data type named Roster// declare a variable of type RosterRoster student;if (student == Sharon)cout << “It’s true”;
2006 C++ Course Handouts January 2006
Notes: 105
2093/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
2103/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Floating Point Round Off ErrorsFact of life when using floating point dataDivide 1 by 3 to two decimals, we get 0.33Multiply 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
2006 C++ Course Handouts January 2006
Notes: 106
2113/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
2123/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Random Number Generator
#include <iostream> // has cout stuff#include <stdlib.h> // Has srand function#include <time.h> // has time functionsusing namespace std;
void main( void ){
cout << "Generate a 100 random numbers\n";srand( (unsigned)time( NULL ) );cout.width(9);cout << rand() << endl;cout.width(9);cout << rand() << endl;cout.width(9);cout << rand() << endl;cout.width(9);cout << rand() << endl;
}
7963
1737
31952
17398
Code tested 07/22/2001
2006 C++ Course Handouts January 2006
Notes: 107
2133/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Let’s See What We Know !!
char x, y, z;main(void){
cout << "Enter a character:";cin >> x;cout << "Enter a character:";cin >> y;cout << "Enter a character:";cin >> z;cout << x << y << z << endl;cout << x + y + z << " Why?" << endl;cout << (int) x << endl;
}
Enter a character:AEnter a character:BEnter a character:CABC198 Why?65
Output…..
2143/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Artificial Intelligence
Reasoning abilityI drove the car into the garage and it died.
Woman, without her man, is lostWoman, 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?
2006 C++ Course Handouts January 2006
Notes: 108
2153/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Review1. 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)
2163/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 through 4 by now2. Read Chapter 5 for next week3. Work on your term paper4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 4 on page 249 of the text. (Chapter 3)
2006 C++ Course Handouts January 2006
Notes: 109
2173/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 4 Summary
Summary of Selection Structures
If StatementIf -- ElseSwitch StatementLogical OperatorsExpressionsGoto StatementEnumerated Types
2183/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 5
Looping in C++
While LoopsDo LoopsFor…Next LoopsContinue StatementBreak StatementGoto StatementTest for Entrance LoopTest for Exit Loop
2006 C++ Course Handouts January 2006
Notes: 110
2193/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
While Loops
Basic Structurewhile (expression)C++ statement
Keeps looping while “expression” is TRUE !Called an “Entry Condition” LoopAlso called a “Test For Entrance” Loop or “Pretest”
LoopWhy?
2203/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
While Loops
Single-statement bodywhile (Expression)
Single Statement;
Multi-statement bodywhile (Expression)
{Statement-1;Statement-2;Statement-3;Statement-n;}
2006 C++ Course Handouts January 2006
Notes: 111
2213/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
2223/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
While Loop Example 2#include <iostream>using namespace std;
void main(){char ch;int x;x = 1;
while (ch != '$'){
cout << "Enter a Character:";cin >> ch;cout << "Count:";cout << x++ << " ";cout << ch << endl;
}}
Enter a Character:ACount:1 AEnter a Character:BCount:2 BEnter a Character:CCount:3 CEnter a Character:WCount:4 WEnter a Character:XCount:5 XEnter a Character:#Count:6 #Enter a Character:$Count:7 $
Output
Verified 04/24/2003
2006 C++ Course Handouts January 2006
Notes: 112
2233/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
While Loop Example 3#include <iostream>#include <iomanip>using namespace std;
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 counterwhile (count <= days) {
float sales;cout << "Enter the sales for day " << count << ": ";cin >> sales;total += sales; // Accumulate running totalcount++; // Increment counter
}cout << fixed << showpoint << setprecision(2);cout << "The total sales are $" << total << endl;return 0;
}
Verified 10/24/2003
2243/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 113
2253/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
An Entry Condition LoopWhat happens in the following example ?
count = 3;while (count <= 5)
{cout << “Current Count:” << count++ << endl;}
While is tested before execution
2263/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Caution!
What happens in this example ?
count = 3;while (count <= 5)
cout << “Current Count:” << count << endl;count++;
2006 C++ Course Handouts January 2006
Notes: 114
2273/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Caution!
What happens in this example ?
count = 3;while (count = 5)
cout << “Current Count:” << count++ << endl;
2283/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Common Problems Using Loops
Common Problem (Not Incrementing Counter Variables)x=0;while (x<100)
cout << x;
Un-initialized counter variablesint count;while (count>0)
{Statement-1;Statement-2;}
Forgetting braces around multi-statement loops
2006 C++ Course Handouts January 2006
Notes: 115
2293/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Do WhileTwo Formats for the “Do While”do {
statement-1;statement-2;statement-n;
} while (Boolean Expression);
dostatement-1;
while (Boolean Expression);
Keeps looping while “expression” is TRUE !Called an “Exit Condition” LoopAlso called a “Test For Exit” LoopWhy?
2303/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Do While
count = 0;do
{cout << “Current Count:” << count << endl;count++;}
while (count <= 5);
An Exit Condition Loop
2006 C++ Course Handouts January 2006
Notes: 116
2313/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;
}
2323/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Test for Entrance or Exit
Test for exitcount = 9;do
cout << “Current Count:” << count++ << endl;while (count < 5);
Test for entrancecount = 9;while (count < 5)
cout << “Current Count:” << count++ << endl;
2006 C++ Course Handouts January 2006
Notes: 117
2333/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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. DOtest all loops to make sure they do what you expect.
More Complicated while StatementsThe 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
2343/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Determine the Min and Max on the Fly
double number_in, max, min; int i=0;
Void main(){
// Establish test variablesmin=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 valueswhile (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 resultscout << "Highest number entered is: " << max;cout << " Lowest number entered is: " << min << endl;
2006 C++ Course Handouts January 2006
Notes: 118
2353/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The “For Loop”
General Syntax:for (initialize; test; update action)
Other C++ statements
The loop is repeated until the test is falseExamples:
for (n=0; n<100; n++)cout << n << “\n”;
for (n=100; n>10; n--)cout << n << “\n”;
2363/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
For Loop
Single-statement bodyfor (Initialization; Boolean Test; Update Action)
Single Statement;
Multi-statement bodyfor (Initialization; Boolean Test; Update Action)
{Statement-1;Statement-2;Statement-3;Statement-n;}
2006 C++ Course Handouts January 2006
Notes: 119
2373/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
For Loop
Examplesfor (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;}
2383/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
For Loop
Examplesfor (count=0; count<1000 && x>10; count++)
Statement-1;
for (int i=110; i<180; i=i+10){Statement-1;Statement-2;Statement-n;}
2006 C++ Course Handouts January 2006
Notes: 120
2393/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
For Loop
Common Problemfor (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
2403/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Multi-parameter for LoopsThe for StatementThe 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;}
}
2006 C++ Course Handouts January 2006
Notes: 121
2413/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
2423/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 << y << " " << x << endl;
}
Output0 00 10 20 30 41 01 11 21 31 42 02 12 22 32 43 03 13 23 33 44 04 14 24 34 4
Code Verified 6/21/2001
2006 C++ Course Handouts January 2006
Notes: 122
2433/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
2443/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
continue statement
Example of continue statement
#include <iostream>using namespace std;
int x;
int main(void){x = 0; while (x < 20)
{x++;if (x == 1 || x == 2)
continue;cout << "Value of x is " << x << endl;
}}
Continue forces the next iteration of the loop.
Code verified 6/21/01
Value of x is 3Value of x is 4Value of x is 5Value of x is 6Value of x is 7Value of x is 8Value of x is 9Value of x is 10Value of x is 11Value of x is 12Value of x is 13Value of x is 14Value of x is 15Value of x is 16Value of x is 17Value of x is 18Value of x is 19Value of x is 20
Generated Output
2006 C++ Course Handouts January 2006
Notes: 123
2453/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Break StatementExamplecount = 100;while (1)
{if (count == 0)
break;count--;cout << count << endl;}
While is always evaluated to trueBreak used to “Get Out”Count is is used then decremented
2463/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
continue and break
continue and breakAt 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.
2006 C++ Course Handouts January 2006
Notes: 124
2473/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);
2483/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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?
2006 C++ Course Handouts January 2006
Notes: 125
2493/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 through 5 by now2. Read Chapter 6 for next week3. Work on your term paper4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 9 on page 310 of the text. (Chapter 3)
2503/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 5 Summary
Summary of Looping Structures
While loopsFor loopsDo – WhileNested LoopsTest for EntranceTest for ExitCounters
2006 C++ Course Handouts January 2006
Notes: 126
2513/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Section 4b
Encryption Fundamentals
Brute Force attackCaesar’s CipherXOR CipherCode ObfuscationVigenère CipherRandom Mono-alphabet Cipher
2523/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Data Security Through EncryptionThe 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,00064 bit = 256-1 = 1.844674407x1019 or 18,446,744,070,000,000,000128 bit = 2128-1 = 3.402823669x1038 or …
DES 64-bitTriple DES 128-bitRijndael 64-bitRC2 64-bit
2006 C++ Course Handouts January 2006
Notes: 127
2533/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 fileUse a dictionary of over a million words to
try each password
2543/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 easyUse a key from 1 to 25 and make an offset from each letter.Called the Caesar CipherSay, we choose 4 as the keyA becomes E, B becomes F, C becomes G, etcAll sorts of schemes for short runs of dataSay, we have a 10-byte product keyAdd 1 to the 1st byte, 2 to the 2nd, 3 to the 3rd, and so on
2006 C++ Course Handouts January 2006
Notes: 128
2553/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Basic Encryption (Caesar’s Cipher)
Key of 3A B C D E F G H I J K L M N O P Q R S T U V W X Y ZD 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 becomesPHHW PH DW PLGQLJKW
Easy to crackLinguistic patterns are obviousE is the most common letter, followed by t, a,
o, nT is the most common letter to begin a word
2563/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Encryption – Random Mono-Alphabet
Random Mono-alphabet CipherPick a word to use as the key, FEATHER, for exampleRemove duplicate letters leaving, FEATHRUse FEATHR to start then use remaining letters starting from
right to left
ABCDEFGHIJKLMNOPQRSTUVWXYZFEATHRZYXWVUSQPONMLKJIGDCB
2006 C++ Course Handouts January 2006
Notes: 129
2573/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Encryption -- Vigenère Cipher
Vigenère CipherPick a word for the key, say TIGERUse the ‘T’ as the starting offset
ABCDEFGHIJKLMNOPQRSTUVWXYZTUVWXYZABCDEFGHIJKLMNOPQRS
Then do it again using ‘I’ as the starting offsetABCDEFGHIJKLMNOPQRSTUVWXYZIJKLMNOPQRSTUVWXYZABCDEFGH
Then again using G and then E and RThe word CAT becomes
VTMDBU
And so on..
2583/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Basic Encryption (XOR Cipher)
Take each byte and XOR it with a number, say 6, for example
A 65 01000001XOR 06 00000110G 72 01000111
2006 C++ Course Handouts January 2006
Notes: 130
2593/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Basic Encryption (XOR Cipher)
How do you do this with C++?
char ch=‘A’char key=6;char newchar;
newchar = ch ^ key;cout << newchar;
Exclusive OR
2603/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Basic Encryption (XOR Cipher)
How would you process an XOR encrypted file without knowing the specific key?
1. Open the message or file2. 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
2006 C++ Course Handouts January 2006
Notes: 131
2613/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;
for (i=0; i<MAX; i++){
encrypted[i]='\0';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;}
Original Message:ABCD1234-2004Encrypted:LONI<?>9 ?==9
Decrypted:ABCD1234-2004
Code Verified 09/28/2004
2623/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
CERT Coordination Center
http://www.cert.org/advisories/Carnegie Melon University Software Engineering
InstituteSeveral hundred per year are publishedIt is stated that 85% of the CERT advisories could have
been prevented by using cryptographyBlack-box tests, White-box tests, Red Team Testing
2006 C++ Course Handouts January 2006
Notes: 132
2633/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Encryption Summary
Summary of Encryption
Brute Force attackCaesar’s CipherXOR CipherCode ObfuscationVigenère CipherRandom Mono-alphabet Cipher
2643/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 6
Functions
Top Down DesignPredefined FunctionsUser-Defined FunctionsBlack Box AnalogyScopeCall by ValueCall by ReferenceFunction Overloading
2006 C++ Course Handouts January 2006
Notes: 133
2653/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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?
2663/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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.
2006 C++ Course Handouts January 2006
Notes: 134
2673/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Black Box Effect of Functions
Black Box EffectThevenin’s Theorem in Engineering
Pass in Some Data Function Return A Result
2683/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Analogous to a Mathematics Function
y = mx + bWhere
y is the return valuem, x and b are passed arguments
Arguments can be numeric, character, etcReturn values can be numeric or character
2006 C++ Course Handouts January 2006
Notes: 135
2693/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Functions - Syntax
Function Definition:return_type function_name (arg1_type arg-1, arg2_type
arg-2, arg-n..){
C++ statements..return(value);
}
2703/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Functions – 3 PartsThe Prototype:return_type function_name(arguments);
Function Call:receiving_variable = function_name(arguments);
Function Definition:return_type function_name(arguments){
C++ statements;return(value);
}
2006 C++ Course Handouts January 2006
Notes: 136
2713/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Functions - Syntax
Example showing integer return valueint result;Prototype:int squared(int x);
Calling a Function:result = squared(10);
Function:int squared(int x){
x=x*x;return(x);
}
2723/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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.
2006 C++ Course Handouts January 2006
Notes: 137
2733/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Prototype Variations
Prototype Variationsint 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
2743/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Functions - No Arguments
#include <iostream>using namespace std;void put_asterisk(void);
int i;
int main(){
put_asterisk();put_asterisk();put_asterisk();return(0);
}
void put_asterisk(){
cout << “*”;}
Note: void means no argument expected
Note
Passed Nothing
Returns Nothing
2006 C++ Course Handouts January 2006
Notes: 138
2753/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Functions - Global Variables// code verified 10/31/2002#include <iostream>using namespace std;void put_asterisk(char ch); // prototypeint i;char ch4='!';
void main(){ char ch1='*';char ch2='$';char ch3='A';
put_asterisk(ch1); // function callput_asterisk(ch2);put_asterisk(ch3);
}
// Function to print the character that is passedvoid put_asterisk(char ch) // definition{
cout << ch << ch4 << endl;}
Code Verified 5/31/2001
Generated Output*!$!A!
2763/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Functions - Return Values// code verified 10/31/2002include <iostream>using namespace std;float num1, num2, ans;float calc(float a, float b); // Function prototype
void main(void){
num1=12.1;num2=9.9;ans=calc(num1, num2);cout << "The returned value is: " << ans <<endl;
}
// Define the actual functionfloat calc(float num1, float num2){
float answer;cout << "The passed values are: " << num1 << " " << num2 << endl;answer = (num1-num2)/(num1*num2);return(answer);
}
Generated OutputThe passed values are: 12.1 9.9The returned value is: 0.0183655
2006 C++ Course Handouts January 2006
Notes: 139
2773/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;}
2783/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Pre-defined Functions
int x=25;float y=3.2;
sqrt(x) returns 5pow(2, 5) returns 32abs(-9) returns 9labs(-90000) returns 90000fabs(-7.56) returns 7.56ceil(y) returns 4.0 rounded upceil(3.9) returns 4.0 rounded upfloor(y) returns 3.0 rounded downfloor(3.9) returns 3.0 rounded down
2006 C++ Course Handouts January 2006
Notes: 140
2793/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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.“);
2803/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 asan 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.
2006 C++ Course Handouts January 2006
Notes: 141
2813/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
System Function v. Programmer Defined// code verified 10/31/2002#include <iostream>using namespace std;int y = 60;int displaytext(void);void main(void){
int x = 100;cout << "Displaytext Returns " << displaytext();cout << endl;
}
// Programmer defined functiondisplaytext(){
int x = 90;cout << "x=" << x << " y=" << y << endl;return(x);
}
Return and main are system functions
Outputx=90 y=60DisplaytextReturns 90
2823/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Default Arguments#include <iostream>using namespace std;
void displayStars(int = 10, int = 1);
void main(){
displayStars(); // Uses default values cols and rowscout << endl;displayStars(5); // Uses 5 for cols and default value for rowscout << 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;}
}
2006 C++ Course Handouts January 2006
Notes: 142
2833/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Graphical RepresentationWindows
or
DOSFunction A
Function D
Function CFunction B
Main()
2843/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Variable Scope// code verified 10/31/2002#include <iostream>int y = 60; // Global Variableint displaytext(int abc); // prototype scopevoid main(void){
int x = 10; // Local to the maincout << "Displaytext Returns " << displaytext(x);cout << endl;
}
// Programmer defined functiondisplaytext(int abc){
int x = 90; // local to the functioncout << "x=" << x << " y=" << y << " abc=" << abc << endl;return(x);
}
Generated Outputx=90 y=60 abc=10Displaytext Returns 90
2006 C++ Course Handouts January 2006
Notes: 143
2853/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Variable Scope
File Scope GlobalFunction Scope Local to functionBlock Scope Local to surrounding blockPrototype Scope Local to prototype only
2863/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Local and Global VariablesLocal 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 localvariables 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 VariablesVariables 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 nameas 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.
2006 C++ Course Handouts January 2006
Notes: 144
2873/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 envpint main(int argc, char *argv[], char *envp[]){
int cost_of_goods_sold=0.0; // local to the mainint i=0;{
int i=10; // local to blockcout << cube_it(i) << endl;return(0);
}}
int cube_it(int c){
int cubed_value=0; // local to the functioncubed_value=c*c*c;return(cubed_value);
} Code Verified 10/31/2001
2883/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The Return Statement
#include <iostream>using namespace std;
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);
}
Code Verified 5/31/2001
2006 C++ Course Handouts January 2006
Notes: 145
2893/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Return Values
Several forms of return statements
return 5; // returns 5return (5); // returns 5return (x > 5); // returns true if x > 5return (MyFunction()); // calls MyFunctionreturn; // simply bails out
2903/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
elsecout << customer_name << " " << kwh << endl;
}
2006 C++ Course Handouts January 2006
Notes: 146
2913/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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++;
}
2923/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Automatic Local Variables (Default)#include <iostream>using namespace std;
void showVariable();
int main(){
for (int count = 0; count < 9; count++)showVariable();
return 0;}
void showVariable(){
int myNum=0;
cout << "StatNum is " << myNum << endl;myNum++;
}
Generated Output:StatNum is 0StatNum is 0StatNum is 0StatNum is 0StatNum is 0StatNum is 0StatNum is 0StatNum is 0StatNum is 0
2006 C++ Course Handouts January 2006
Notes: 147
2933/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Static Local Variables#include <iostream>using namespace std;
void showVariable();
int main(){
for (int count = 0; count < 9; count++)showVariable();
return 0;}
void showVariable(){
static int myNum=0;
cout << "StatNum is " << myNum << endl;myNum++;
}
Generated Output:StatNum is 0StatNum is 1StatNum is 2StatNum is 3StatNum is 4StatNum is 5StatNum is 6StatNum is 7StatNum is 8
2943/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Break
2006 C++ Course Handouts January 2006
Notes: 148
2953/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Call by Value// code verified 10/31/2002int a,b;void swap(int x, int y);
void main(void){
a=100;b=200;cout << "a=" << a << endl;cout << "b=" << b << endl;swap(a, b);cout << "a=" << a << endl;cout << "b=" << b << endl;
}
void swap(int x, int y){
int hold;hold=x;x=y;y=hold;
}
Generated Outputa=100b=200a=100b=200
OutputA=100B=200A=100B=200
Arguments NOT Affected
2963/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Call By Reference Example// Example of Call by Reference Functions#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 argumentsvoid get_input(int& num1, int& num2){
cout << "Enter Number 1:";cin >> num1;cout << "Enter Number 2:";cin >> num2;
}
Actual values of first_num and second_num are modified within the function and the arguments themselves are modified.
Code verified 6/26/2001
2006 C++ Course Handouts January 2006
Notes: 149
2973/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Call By Value Example// Example of Call by Value Functions#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 argumentsvoid get_input(int num1, int num2){
cout << "Enter Number 1:";cin >> num1;cout << "Enter Number 2:";cin >> num2;
}
Call by Value is the default function calling method which does NOT modify the arguments. Data is protected.
Code verified 6/26/2001
2983/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Swap Examplevoid get_input(int& n1, int& n2); // Prototype, formal parametersvoid swap(int& n1, int& n2);
void main(void){
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 argumentsvoid 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 argumentsvoid swap(int& num1, int& num2){
int temp;temp = num1;num1 = num2;num2 = temp;
}
Code verified 6/26/2001
2006 C++ Course Handouts January 2006
Notes: 150
2993/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Simulate a Roll of a Die (1 of 2)#include <iostream> // has cout stuff#include <stdlib.h> // Has srand function#include <time.h> // has time functions#include <iomanip> // for setw
using namespace std;const int MAX=1000000;
unsigned x, seed; int roll;double percent;unsigned arr[6];
void main( void ){
// Housekeeping, initialize arrays, etcfor (x=0; x<6; x++)
arr[x]=0;
cout << "Simulate 10 rolls of a die\n";seed = (unsigned)time( NULL );cout << "Seed is " << seed;
// First, print out 30 die throwssrand(seed);for(x = 0; x<30; x++ ){
roll = rand() % 6 + 1;cout << roll << endl;
}
Simulate 30 rolls of a dieSeed is 1099104137211464355465622655141111222263
Code tested 10/22/2004
3003/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Simulate a roll of a die (2 of 2)
// Next simulate 1 million throws and check the distributionsrand(seed);for(x = 0; x<MAX; x++ ){
roll = rand() % 6;arr[roll]++;
}
// Calculate and display distribution and percentagescout << "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.622 167280 16.733 166278 16.634 166102 16.615 167434 16.746 166715 16.67
Code tested 10/22/2004
2006 C++ Course Handouts January 2006
Notes: 151
3013/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);
3023/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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);
}
2006 C++ Course Handouts January 2006
Notes: 152
3033/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Overloading (Polymorphism)#include <iostream>using namespace std;long vector;int counter;float standard_deviation;double mass_of_the_sun;
// Function Prototypesint square(int);long square(long);float square(float);double square(double;
int main(void){
square(counter);square(standard_deviation);square(vector);square(mass_of_the_sun);
}
Note same function name but different argument types
Called Polymorphism
3043/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Overloadingint square(int q) {
return(q*q);}
float square(float q) {return(q*q);
}
long square(long q) {return(q*q);}
double square(double q) {return(q*q);
}
Note here, in C++, the function names are all the same. Only the return types and argument lists are different.
2006 C++ Course Handouts January 2006
Notes: 153
3053/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Overloadingint 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);
}
3063/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Overloadingbool 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);
}
2006 C++ Course Handouts January 2006
Notes: 154
3073/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Templates, Embedded#include <iostream>using namespace std;
// Get input data templatetemplate <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;
}
Code Tested 10/03/2004
3083/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Templates, Header Files#include <iostream>using namespace std;
#include <c:/progs/square_template.h> // squared template
// Main Logic Areavoid 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;
cout << "Completed...\n\n";}
Code Tested 10/03/2004
// Get input data templatetemplate <class T1>
T1 square(T1 number){
T1 result;result = number * number;
return(result);}
2006 C++ Course Handouts January 2006
Notes: 155
3093/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Templates, Header Files#include <iostream>#include <iomanip>
using namespace std;
#include <c:/progs/Swap_template.h> // squared template
// Main Logic Areavoid 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";}
Code Tested 10/03/2004
//Get input data templatetemplate <class T1>void square(T1 &x, T1 &y){
T1 temp;temp = x;x = y;y = temp;
}
3103/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Function Templates, System Supplied
#include <iostream>#include <iomanip>#include <algorithm> // system supplied swap template
using namespace std;
// Main Logic Areavoid 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";}
Code Tested 10/03/2004
2006 C++ Course Handouts January 2006
Notes: 156
3113/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);
return(0);}
int cube_it(int x){
int value;value= x * x * x;cout << value;return(value);
}
3123/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Review Questions1. 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?
2006 C++ Course Handouts January 2006
Notes: 157
3133/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 through 6 by now2. Read Chapter 7 for next week3. 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)
3143/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 6 Summary
C++ Functions
Built-in FunctionsUser Defined FunctionsDefinitionsPrototypesCalling by ReferenceCalling by ValueOverloading
2006 C++ Course Handouts January 2006
Notes: 158
3153/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 7Data Structures and Classes
ClassesEncapsulationConstructorsStruct Type
3163/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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.
2006 C++ Course Handouts January 2006
Notes: 159
3173/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Data Structures
struct CDAccount // Structure Tag or Template{
double balance; // Member Namesdouble interest_rate;int term;
};
struct CDAccount { // Structure Tag or Templatedouble balance; // Member Namesdouble interest_rate;int term; };
3183/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Data Structures
struct CDAccount // Structure Tag or Template{
double balance; // Member Namesdouble interest_rate;int term;
};
int main(void){CDAccount my_account, your_account; // Structure Variablesfloat cost_of_goods_sold;}
Define the data type
Define the variable
Code verified 11/04/01
2006 C++ Course Handouts January 2006
Notes: 160
3193/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
3203/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 inputcout << "Enter the diameter:";cin >> c.diameter;
// Do calculationsc.radius = c.diameter / 2;c.area = pi * pow(c.radius, 2.0);
// Do Outputcout << fixed << showpoint << setprecision(2);cout << "Radius: " << setw(6) << c.radius << endl;cout << " Area: " << setw(6) << c.area << endl;}
Code verified 04/14/03
2006 C++ Course Handouts January 2006
Notes: 161
3213/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
DOT OperatorSyntax:Structure_Variable_Name.Member_Variable_NameExample: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’;your_record.student_age=32;
}
Code verified 11/04/01
3223/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Initializing a Structurestruct 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
2006 C++ Course Handouts January 2006
Notes: 162
3233/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Data Structures#include <iostream>using namespace std;
struct book { // Structure Templatechar 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
3243/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Alternate Way of Declaring Structure Variables
struct book { // Structure Templatechar title[30];char author[25];int quantity;float cost;} library; // Structure Variable
Code verified 11/04/01
2006 C++ Course Handouts January 2006
Notes: 163
3253/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Passing Structure Members to Functions#include <iostream>using namespace std;struct book
{ // Structure Templatechar 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 costfloat invcost(int quan, float cost){
return(quan * cost);}
Validated 7/13/2001
3263/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
#include <iostream>using namespace std;
struct book { // Structure Templatechar title[30];char author[25];int quantity;float cost;} library; // Structure Variable
// Prototypesfloat 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
Passing Structure Members to Functions
2006 C++ Course Handouts January 2006
Notes: 164
3273/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
struct Circle{
float radius;float diameter;float area;
};
Circle getInfo();
const double pi = 3.14159;
void main(){
Circle c1, c2;
c1 = getInfo();c2 = getInfo();
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;}
Validated 11/22/2003
Returning a Structure From a Function (1 of 2)
1 of 2
3283/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Circle getInfo() {
Circle round; cout << "Enter the diameter of a circle: ";cin >> round.diameter;round.radius = round.diameter / 2;return round;
}
Validated 11/22/2003
Returning a Structure From a Function (2 of 2)
Enter the diameter of a circle: 32Enter the diameter of a circle: 43
The radius and area of the circles areCircle 1 -- Radius: 16.00 Area: 804.25Circle 2 -- Radius: 21.50 Area: 1452.20
2006 C++ Course Handouts January 2006
Notes: 165
3293/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Nested Structuresstruct ChkDate
{int year;int month;int day; }; // Structure Variable
struct book { // Structure Templatechar 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}; // initializingcout << library.check_out.day;cout << date.year << endl;
}
Validated 11/04/2001
3303/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Nested Structuresstruct AnnualCostInfo{
float food, medical, license, misc;};
struct PetInfo{
string name;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;
}
Validated 11/22/2003
Annual costs for my 5-year-old cat Sassy are $457.00
2006 C++ Course Handouts January 2006
Notes: 166
3313/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Structure Constructorsstruct Employee{
int employees;int year;float payrate;
Employee(){
employees =120;year =2004;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;
}
Validated 11/22/2003
Employees: 120Fiscal Year: 2004
Starting Rate: 25.55
3323/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Structure Constructors#include <iostream.h>struct Employee{
int employees;int year;float payrate;
Employee(int e, int y, float p){
employees =e;year =y;payrate =p;
}};
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;
}
Validated 11/22/2003
Structure constructors accept arguments, too
2006 C++ Course Handouts January 2006
Notes: 167
3333/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Structures as Bit FieldsStructures 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 1unsigned field2 : 1;unsigned field3 : 3; // max value is 7unsigned field4 : 3;
} mybits;
3343/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Structures as Bit Fields
struct {unsigned first : 1;
: 2;unsigned second : 1;
: 3;unsigned third : 2;
} gaps;
Max Values for some bit fieldsBits Maximum Value1 12 33 74 155 316 63
2006 C++ Course Handouts January 2006
Notes: 168
3353/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Structures as Bit FieldsPC Configuration switchesstruct 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; };
3363/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Unions (1 of 2)
#include <iostream>#include <iomanip>using namespace std;
union PaySource // Declare a union.{
short hours; // These two variables sharefloat sales; // the same memory space.
};
Validated 11/22/2003
Unions variables share the same memory space
1 of 2
2006 C++ Course Handouts January 2006
Notes: 169
3373/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Unions (2 of 2)void main(){
PaySource employee1; // employee1 is a PaySource union.
char hourlyType; // 'y' if hourly, 'n' if on commissionfloat 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;cout << "How many hours were worked? ";cin >> employee1.hours;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
Shares the same memory space
3383/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 170
3393/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Inheritance & Reuse
When engineers build a new car they reuse many componentsThey modify an existing modelIn C++ a new data type can be declared which is an extension of an existing data typeThis done through the use of inheritance
3403/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Classes
Classes hold member functions as well as variables
Syntax
class class_name{public:
member specification-1member specification-2member specification-3member specification-n
private:member specification-n+1member specification-n+2member specification-n+3member specification-n+4
};
2006 C++ Course Handouts January 2006
Notes: 171
3413/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Classes
Classes hold member functions as well as variablesclass class_name{public:
member specification-1member specification-2member specification-3member specification-n
private:member specification-n+1member specification-n+2member specification-n+3member specification-n+4
};
int main(void){
class_name object_name;}
Once a class is defined, an object is created. An object
is similar to a variable of the class type
3423/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
ClassesClasses hold member functions as well as variables#include <iostream>using namespace std;
class DayOfYear{public: // Public members
void output(); // member function prototypeint month;int day;int year;
private:float cost;
};
DayOfYear today, birthday; // Declare abstract variablesint main(void){
cin >> today.month;cin >> today.day;cin >> today.year;today.output();
}
void DayOfYear::output() // Member Function{
cout << month << "/" << day << "/" << year << cost << endl;}
Code verified 11/04/2001
Scope Resolution Operator
2006 C++ Course Handouts January 2006
Notes: 172
3433/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Classes#include <iostream>using namespace std;
class DayOfYear{public: // Public members
void output(); // member function prototypeint month; // variablesint day;int year;
private:float cost; // Can only be used in member functions
};
DayOfYear today, birthday; // Declare abstract variablesvoid 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;
today.output();birthday.output();
}
void DayOfYear::output() // Member Function{
cout << month << "/" << day << "/" << year << endl;cout << cost << endl;
}
Code verified 11/06/2001
Classes hold member functions as well as variables
3443/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Classesclass DayOfYear{public:
void output(); // member function prototypevoid get_dates(); // member function prototypeint month;int day;int year;
private:int birth_year;
};
DayOfYear today, birthday; // Declare abstract variablesvoid main(void){
today.get_dates(); // Load todaytoday.output(); // Dump todaybirthday.get_dates(); // Load birthdaybirthday.output(); // Dump birthday
}
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;
}
void DayOfYear::output() // Member Function{
cout << month << "/" << day << "/" << year << endl;cout << birth_year << endl << endl;
}
Private Members
Code verified 11/06/2001
Birth_year can be accessed because it is used within the member function
2006 C++ Course Handouts January 2006
Notes: 173
3453/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
ConstructorsUsed to initialize classesMust be in the public section of the classCannot 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 constructorvoidoutput(ostream&, outs);
private:double balance;double interest_rate;
};
3463/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Constructors
int main(void){
BankAccount account1(100, 2.3); // Call the constructorBankAccount account2; // Call default constructorBankAccount account3(500, 99, 6.6); // Call a constructor
account3 = BankAccount(999, 99, 5.5);account1 = BankAccount(1000, 7.6);
}
2006 C++ Course Handouts January 2006
Notes: 174
3473/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;
}
3483/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;};
2006 C++ Course Handouts January 2006
Notes: 175
3493/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;
}
3503/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
}
2006 C++ Course Handouts January 2006
Notes: 176
3513/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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();
}
3523/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Review Questions#include <iostream>using namespace std;
structure book {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;
}
Find the error in the following structure
2006 C++ Course Handouts January 2006
Notes: 177
3533/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Review Questions#include <iostream>using namespace std;
class DayOfYear{public:
void output(); // member function prototypevoid get_dates(); // member function prototypeint month;int day;int year;
private:int birth_year;
};
DayOfYear today, birthday; // Declare abstract variablesvoid main(void){
today.get_dates(); // Load todaytoday.output(); // Dump todaybirthday.get_dates(); // Load birthdaybirthday.output(); // Dump birthdaycin >> 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;
}
Find the error in the following class
3543/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 through 7 by now2. Read Chapter 8 for next week3. Work on your term paper
2006 C++ Course Handouts January 2006
Notes: 178
3553/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 7 Summary
Classes & Data Structures
ClassesConstructorsStructuresInitializing StructuresPassing Structures as Arguments
3563/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 8
Arrays, Single and Multidimensional
Single Dimension ArraysMulti Dimension ArraysDynamic Arrays
2006 C++ Course Handouts January 2006
Notes: 179
3573/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays
An array is used to process a collection of data with the same data type.
ExamplesList of test scores or temperaturesList of names or addresses
3583/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays
Scalar Variablesint count;int day;float cost;char letter;
Arraysint days[6];
1234
31
34.55
W
Each variable of a scalar takes one location
0th 1st 2nd 3rd 4th 5th 6th
123 322 332 455 122 32 432
2006 C++ Course Handouts January 2006
Notes: 180
3593/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays
Declaring an Array#define SIZE 100char 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];
3603/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays
Declaring an Arrayint score[5];
Same As:int score1;int score2; int score3; int score4; int score5;
Like declaring 5 different, but similar variables.
Arrays work very well when trying to do 1000’s of declarations
2006 C++ Course Handouts January 2006
Notes: 181
3613/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Internally, looks like this . . . .
0080 00000000 score[0]0081 000000000082 00000000 score[1]0083 000000000084 00000000 score[2]0085 000000000086 00000000 score[3]0087 000000000088 00000000 score[4]0089 00000000008A 00000000008B 00000000008C 00000000008D 00000000
Assuming a 2-byte integer. Some machines
now use 4 bytes for integers.
3623/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Common Error
Declaring an Arrayint score[5];
score[5]; // index out of bounds
index = 12;score[index];
2006 C++ Course Handouts January 2006
Notes: 182
3633/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Common Errorint 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
0 0 0 0 0 0 0
0th 1st 2nd 3rd 4th i variable
2 4 6 8 10 1000 0Before �
After �
Trouble Here
3643/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays
#include <iostream>#include <iomanip>#include <string>#define MONTHS 12
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 i;
for (i=0; i<MONTHS; i++){cout << setw(16) << left << month[i] << " has ";cout << setw(4) << right << days[i] << " days.\n";}
}
January has 31 days.February has 28 days.March has 31 days.April has 30 days.May has 31 days.June has 30 days.July has 31 days.August has 31 days.September has 30 days.October has 31 days.November has 30 days.December has 31 days.
2006 C++ Course Handouts January 2006
Notes: 183
3653/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays
#include <iostream>#include <iomanip>#include <string>#define MONTHS 12
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;
}
Enter the Month to Print(1-12): 2You requested February
3663/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays
100 101 102 103 104 105 106 107 108 109
#include <iostream> // for cout#include <iomanip> // for setw
void main(){int numbers[10];int i, x;i = 0;x = 100;
for (i=0; i<10; i++)numbers[i]=x++;
for (i=0; i<10; i++)cout << i << setw(5) << numbers[i] << endl;
}
0 1001 1012 1023 1034 1045 1056 1067 1078 1089 109
2006 C++ Course Handouts January 2006
Notes: 184
3673/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Array Initialization#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 arraysize = sizeof(vectors) / sizeof(long);for (n=0; n<size; n++)
vectors[n]=0;
cout << sizeof(vectors) << endl;cout << sizeof(long) << endl;cout << size << endl;}
Also, can be read in from a disk file
Code verified 11/17/2001
3683/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Initializing Arrays
Initializing a one dimensional array of integersint testscores[10] = {98,87,88,89,90,100,76,99,91,81};
Initializing a two dimensional array of integersint matrix[2][3] = {
{43,54,65},{44,65,99}}
int matrix[2][3] = {{43,54,65},{44,65,99}}
2006 C++ Course Handouts January 2006
Notes: 185
3693/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Initializing Arrays
You initialize this array by writingint 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} };
3703/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Common Error
Indexes always start at zero in C or C++Called, zero relativeMost languages start at 1 (COBOL, VB, FORTRAN)
Fence Post ErrorsIt 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)
2006 C++ Course Handouts January 2006
Notes: 186
3713/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
3723/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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){
dump_array(test_scores, SIZE);cout << "2 is " << test_scores[2] << endl;return(0);
}
// Pass the address of the array and the sizevoid dump_array(int ar[], int n){int i;for (i=0; i<n; i++)
cout << "Score " << i << " is " << ar[i] << endl;ar[2]=200; // modify element 2}
Generated OutputScore 0 is 98Score 1 is 87Score 2 is 88Score 3 is 89Score 4 is 90Score 5 is 100Score 6 is 76Score 7 is 99Score 8 is 91Score 9 is 812 is 200
Code verified 11/17/2001
2006 C++ Course Handouts January 2006
Notes: 187
3733/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 fourbytes 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, characterand long. Be careful of type struct, though. There are some filler and padding that takes place that is not visible to the programming eye.
3743/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays and Structures#include <iostream>struct windinfo{
double velocity;char direction;long temperature;
};
void main(){windinfo weather[100]; // Array of 100 windinfoint x;
// initialize the structure membersfor (x=0; x<100; x++){
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;
}
Let's print out some sizesWindinfo:16Weather:1600
Velocity:8Direction:1
Temperature:4
Code verified 11/17/2001
2006 C++ Course Handouts January 2006
Notes: 188
3753/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Multidimensional Arrays
char page[30][100];
This array has two indexesThe first is from 0 to 29the second is from 0 to 99page[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]
3763/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Arrays of Strings
char names[45][100];char addresses[45][100];
These arrays have two indexesThe first is from 0 to 44, the second is from 0 to
99names array holds data like:
SmithLeonardWilsonDotolo
2006 C++ Course Handouts January 2006
Notes: 189
3773/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
3783/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Review Questions1. 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
2006 C++ Course Handouts January 2006
Notes: 190
3793/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 through 8 by now2. Read Chapter 9 for next week3. Work on your term paper
3803/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 8 Summary
Arrays Summary
Single DimensionMulti DimensionStatic and Dynamic
2006 C++ Course Handouts January 2006
Notes: 191
3813/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 9 – Sorting & Searching
Sorting Searching Concepts
Exchange SortSelection SortMerge SortQuick SortBinary Search
3823/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Sorting an Array
Many types of sorting algorithmsHashInsertionBubble (Exchange)SelectionShellTournamentShaker Quick SortMerge SortPoly-PhaseCascadeOscillatingCrisscross
Sorting and Sort Systemsby Harold Lorin.
2006 C++ Course Handouts January 2006
Notes: 192
3833/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
3843/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bubble Sort (Exchange Sort)
Bubble Sort Algorithm1. Compare element-0 with
element-12. 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
2006 C++ Course Handouts January 2006
Notes: 193
3853/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 n2algorithm
5. Methods1. Swap2. Needs two loops, inner and
outer
3863/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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(){
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
Know as the n-squared methodAlso known as the exchange sort.
2006 C++ Course Handouts January 2006
Notes: 194
3873/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bubble Sort (2 of 3)// sort the arrayint sort_it(int arr[]){int x, swap;int swaps=0;bool we_swapped_one=false;
// do the sortdo{
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
Know as the n-squared methodAlso known as the exchange sort.
3883/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bubble Sort (3 of 3)
// Initialize the array with random numbersvoid initialize_array(){
int number;
for (int i=0; i<SIZE; i++){number=rand();number = number % 10000;main_array[i]=number;}
}
2006 C++ Course Handouts January 2006
Notes: 195
3893/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Shaker SortShaker Sort Algorithm Discussion1. A Shaker Sort is bi-directional bubble sort
because we work from both ends2. 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
3903/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Selection Sort
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
0 1 2 3 4
2006 C++ Course Handouts January 2006
Notes: 196
3913/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Selection Sort
Algorithm
1. Find the smallest element in the set 0-n
2. Exchange with the zero element3. Find the smallest in 1-n4. Exchange with the 1st element5. Find the smallest in 2-n6. Exchange with the 2nd element7. Find the smallest in 3-n8. Exchange with the 3rd element9. Continue until the n-th element
is reached
3923/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Selection Sort
Selection Sort DiscussionMethods
1. Search for the lowest element starting from nth element2. Swap the lowest element with nth element
The insertion sort is considered to be an n2 algorithm
10 20 30 40 50 60 70 80 90 100N (thousands)
180
150
120
90
60
30
0
2006 C++ Course Handouts January 2006
Notes: 197
3933/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
3943/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Selection Sort Code (2 of 3)// Function to Perform the Selection Sortint 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);
}
2006 C++ Course Handouts January 2006
Notes: 198
3953/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;}
}
3963/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Sort Animation Web SiteDemonstration of Selection, Bubble, Insertion,
Heap, Merge and Quick Sorts
http://www.ship.edu/~cawell/Sorting/selintro.htm
2006 C++ Course Handouts January 2006
Notes: 199
3973/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Searching an Array
Picture a phonebook How would you find a number by name?
Search alphabeticallyHow would you find a name by using a number?
Search linearlyLinear Search
Start at the beginning and test every occurrence
Binary SearchSort the dataSuccessive slicing in half
3983/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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};
int main(void){
size = sizeof(a) / sizeof(int);
for (k=0; k<size; k++){
if (a[k] < 50)cout << "Hit:" << a[k] << endl;
}return(0);
}
OutputHit:32Hit:43Hit:21Hit:23Hit:34Hit:45
2006 C++ Course Handouts January 2006
Notes: 200
3993/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Binary SearchSay we have 100 million phone numbersSort the numbersIf we are looking for 555-480-9400To see how many tests we need we need to use logarithms
Searches = log2x, where x is the total number of itemsSearches = log2100000000 for example
How to solve:Searches = Log10100000000 / Log102Searches = 8 / 0.301029996Searches = 26.57 or rounded up to 27
From Log conversion formula (Applied Mathematics, p 1.6)logb(x) = loga(x)/loga(b)
4003/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Binary SearchFirst, Sort the dataThen, by successively cutting the array of data in half, you can narrow
down the search1. Say we are looking for 3032. See how any elements are in the array3. Choose the middle position (5 in this case)4. Compare the value at 5 (333) against the search argument (303)
204222303321324333356411444504621
Num(0)Num(1)Num(2)Num(3)Num(4)Num(5)Num(6)Num(7)Num(8)Num(9)Num(10)
Middle Position
2006 C++ Course Handouts January 2006
Notes: 201
4013/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
4023/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Binary Search Example ( 2 of 4)// Binary Search Functionint 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;}
2006 C++ Course Handouts January 2006
Notes: 202
4033/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Binary Search Example ( 3 of 4)
// Initialize the array with random numbersvoid initialize_array(){
int number;
for (int i=0; i<SIZE; i++){number=rand();number = number % 10000;cout << number << endl;main_array[i]=number;}
}
4043/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Binary Search Example ( 4 of 4)// sort the arrayint sort_it(int arr[]){
int x, swap;int swaps=0;bool we_swapped_one=false;
// do the sortdo{
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
2006 C++ Course Handouts January 2006
Notes: 203
4053/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Indexed Files and SQL Indexes
1. An Indexed File has two, or more, parts2. Data is kept in the Data Part in Birth Order3. A separate file of keys is maintained for each key field (index field)4. Sometimes there can be several key files
Data Part
4063/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 9 Summary
Sorting and Searching
Bubble SortsSelection SortsBinary Search
2006 C++ Course Handouts January 2006
Notes: 204
4073/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 10 – C++ Strings
Character Arrays & String Class
StringsCharacter ArraysString FunctionsString Class
4083/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Basics
A String Literal: cout << “Hello”
A cstring variable: char book_title[30];
Null Character, \0Also known as low-values
2006 C++ Course Handouts January 2006
Notes: 205
4093/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Function Previewgets() 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
4103/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Data
#include <iostream> using namespace std;char name[40]; // 40 characterschar address[50]; // 50 characterschar state[3];
int main(void){
state[0]=‘A’;state[1]=‘Z’;state[2]=0;strcpy(name, ”Will Smith ”);strcpy(address, “1234 W. Pecos ”);cout << name << address << state << endl;
}
0 is same as null is same as ‘\0’
Strings in C++ are no more than an array of characters.
2006 C++ Course Handouts January 2006
Notes: 206
4113/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Data Using C++#include <iostream>using namespace std;
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
Strings in C++ are no more than an array of characters.
4123/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Strings in C++
char name[20] = “SMITH “;
terminated with low-values or binary zero \0called ASCIIZ strings
ASCII Data Followed by a Binary Zerostring functions will insert appropriate \0 (NULL)if you are building your own strings, you must insert \0strings are zero relative
Example:name[5]=‘\0’; // optionally name[5]=0;
cout << name << endl’
2006 C++ Course Handouts January 2006
Notes: 207
4133/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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
4143/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Difference Between \0 and “0”Binary Zero 00000000 NULL or \0ASCII Zero 00110000 48 or Character Zero
0 48 001100001 49 001100012 50 001100103 51 001100114 52 001101005 53 001101016 54 001101107 55 001101118 56 00111000
2006 C++ Course Handouts January 2006
Notes: 208
4153/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
ASCII v. Numeric
#include <iostream>using namespace std;
void main(){
int counter;
for (counter=32; counter<255; counter++){
cout.width(1);cout << (char) counter;cout.width(4);cout << counter << endl;
}}
Code verified 11/23/2003
32! 33" 34# 35$ 36% 37& 38' 39( 40) 41* 42+ 43, 44- 45. 46/ 470 481 492 503 514 525 536 547 55
4163/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
ASCII v. Numeric
2006 C++ Course Handouts January 2006
Notes: 209
4173/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String or Character
char ch;
ch = ‘A’; // character A stored in memorych = “A”; // character A followed by \0
ch = A; // loads ch with the variable A
ASCIIAmerican Standard Code for Information Interchange
4183/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Literals
A set of characters“string literal” wrapped on double quotes
Characters wrapped in single quotesStrings wrapped in double quotes
Also called a character arrayMax length ANSI, is 509 bytesMax length, Microsoft, is 2008 bytesAlways end with NULL (Binary Zero, \0)
cout << “This is a string literal..”;char msg1[]=“This is a C string literal”;
2006 C++ Course Handouts January 2006
Notes: 210
4193/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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++ Prototypechar 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.”);
4203/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
strncpy()
prototypestrncpy(strcpy(char *str1, char *str2, int count)
Examplesstrncpy(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.
2006 C++ Course Handouts January 2006
Notes: 211
4213/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
strcat() – String Concatenationchar 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.
4223/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
strncat() – String Concatenationchar 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
2006 C++ Course Handouts January 2006
Notes: 212
4233/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
strcmp() – String ComparisonPrototypeint strcmp(char *str1, char *str2)char message[]="This is a string";// Method Oneif (strcmp(message, "This is a string"))
cout << "Strings are NOT the same\n";else
cout << "Strings are the same\n";
// Method Twoif (strcmp(message, "This is a string") == 0)
cout << "Strings are the same\n";else
cout << "Strings are NOT the same\n";
// Method Threeif (! strcmp(message, "This is a string"))
cout << "Strings are the same\n";else
cout << "Strings are NOT the same\n";
Returns< 0: str1 is less than str2= 0: str1 = str2> 0: str1 is greater than str2
4243/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
strncmp() – String ComparisonPrototypeint strncmp ( const char * string1, const char * string2, int num );char message[]="This is a string";// Method 1if (strncmp(message, "This is", 7))
cout << "Strings are NOT the same\n";else
cout << "Strings are the same\n";
// Method 2if (strncmp(message, "This is a", 9) == 0)
cout << "Strings are the same\n";else
cout << "Strings are NOT the same\n";
// Method 3if (! strncmp(message, "This", 4))
cout << "Strings are the same\n";else
cout << "Strings are NOT the same\n";
Returns< 0: str1 is less than str2= 0: str1 = str2> 0: str1 is greater than str2
2006 C++ Course Handouts January 2006
Notes: 213
4253/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 Arraysmessage = “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”;
4263/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
Proper method:if (strcmp(message, “This is a string”))
cout << “Strings are NOT the same”;else
cout << “Strings are the same”;
< 0: str1 is less than str2= 0: str1 = str2> 0: str1 is greater than str2
2006 C++ Course Handouts January 2006
Notes: 214
4273/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 spacestrlen() 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
4283/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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”;}
2006 C++ Course Handouts January 2006
Notes: 215
4293/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
getchar()reads a character from the keyboard
#define LF 10int 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;}
4303/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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){
x=0;length=strlen(name);
// Write the name oncewhile (x < length)
{putchar(name[x]);x++;}
// Write the name againcout << endl << name << endl;}
Code verified 11/17/2001
2006 C++ Course Handouts January 2006
Notes: 216
4313/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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]This is only a test
EOF is typically -1 when reading data filesCTRL-Z for PC keyboard inputCTRL-D for Unix keyboard input
Code verified 11/17/2001
4323/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
puts() and gets()
Quick and dirty way to obtain text from keyboard and print text to the screen.
puts(stringvar);puts(“Literal”);gets(stringvar);
2006 C++ Course Handouts January 2006
Notes: 217
4333/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
toupper() and tolower()int toupper(int ch) // prototypeint 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;
4343/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Getline Member Function
Member function to read a line of inputSyntax:input_stream.getline (string_var, Max_Characters + 1);
Examples:char st[30];
cin.getline(st, 30);cin.getline(st, sizeof(st));
2006 C++ Course Handouts January 2006
Notes: 218
4353/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
toupper() and tolower() Returns an Intint 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
4363/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 219
4373/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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”);
4383/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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”;
2006 C++ Course Handouts January 2006
Notes: 220
4393/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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”;
4403/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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”;
2006 C++ Course Handouts January 2006
Notes: 221
4413/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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”;
4423/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
atoi(), atol(), atof(), itoa()
ASCII to Integer Conversion Function.Takes in a string argument and returns its integer
equivalent
Syntax:int atoi(string_var);
Example:void main(){
int x=0;char st[7]="654321";x = atoi(st);cout << "Length of String: " << sizeof(st) << endl;cout << "Length of x: " << sizeof(x) << endl;
}
Length of String: 7Length of x: 4
Also: atol & atofPronounced:
A to I, A to L, A to F
itoa for integer to ASCII
2006 C++ Course Handouts January 2006
Notes: 222
4433/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
atoi(), atol(), atof() #include <iostream.h> // for cout#include <stdlib.h> // for atoi, etc
int x;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;
}
Code verified 11/17/2001
4443/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
}
printsCHARLES BABBAGE
2006 C++ Course Handouts January 2006
Notes: 223
4453/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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;
}
printscharles babbage
4463/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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);
}
2006 C++ Course Handouts January 2006
Notes: 224
4473/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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”;
4483/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 OutputThe portion of 'cabbage' containing only a, b, or c is 5 bytes
longCourtesy MSDN Online
2006 C++ Course Handouts January 2006
Notes: 225
4493/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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];memcpy(array, buffer, 1000);
Not in Book
4503/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Class
#include <string>#include <iostream>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";
}
Code Verified 10/29/2002
2006 C++ Course Handouts January 2006
Notes: 226
4513/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String ClassMember FunctionsAtAppendAssignBeginCopyCapacityCompareEndEraseFindInsertLengthReplaceSizeSwapSubstr
4523/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Class#include <string>#include <iostream>using namespace std;
int main(void){string first_name, last_name;string whole_name;
first_name="Allen";last_name="Shepard";whole_name=last_name;whole_name.append(", ");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 commacout << whole_name << endl;
whole_name.at(7)=0; // chops off the last namecout << whole_name << endl;}
Allen 5 31
Shepard, Allen
Shepard Allen
Shepard
Generated Output
2006 C++ Course Handouts January 2006
Notes: 227
4533/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
String Class#include <string>#include <iostream>using namespace std;
void main(void){string first_name, last_name;string whole_name;long ptr;
first_name="Allen";last_name="Shepard";whole_name=last_name;whole_name.append(", ");
// append starting at 0, for 2 byteswhole_name.append(first_name,0,2);
// erase 1 char starting pos 2, compress the strwhole_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;}
}
Shpard, Al
3
ShpQrd, Al
Generated Output
4543/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Review Questions1. Strings in C++ are simply ___________ arrays2. A binary zero is 000000002 or 001100002
3. String Literals are wrapped with ______ quotes4. 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 strings11. What String Class Member Function can be used to replace a
specific character in a string
2006 C++ Course Handouts January 2006
Notes: 228
4553/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 through 10 and 12 by now2. Work on your term paper3. Work on Packet-3…
4563/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 12 Summary
Everything you ever wanted to know about C++ string manipulation, but were afraid to ask.
String Class
StringsString FunctionsC++ String Class
2006 C++ Course Handouts January 2006
Notes: 229
4573/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 13
Files, I/O Streams, Advanced I/O
Stream I/OCharacter I/OInheritance
4583/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
C++ General I/O
Data stored in disk filesC++ used to read in and write out dataPrograms “read in” data from a file to a programPrograms “write out” data from the program to a disk fileIn other words, the I/O is program relative
C++ Program Disk File
2006 C++ Course Handouts January 2006
Notes: 230
4593/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
File and Record Hierarchy1. Databases contain sets of related files2. Files contain records3. Records contain fields4. Fields contain characters (bytes)5. Bytes are made up of bits6. Bits
Think of a File Cabinet (Database)Contains Drawers (Files)Contains Folders (Records)
4603/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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";outstream << "Michael Faraday\n";outstream << "Alexander Graham Bell\n";outstream << "Jimi Hendrix\n";outstream << "Kurt Cobain\n";outstream.close();
}
Code Verified 05/12/2003
Albert EinsteinMichael FaradayAlexander Graham BellJimi HendrixKurt Cobain
2006 C++ Course Handouts January 2006
Notes: 231
4613/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Introduction to Files (Reading)
#include <iostream>#include <fstream>#include <string>using namespace std;
void main(void){
ifstream instream; // output file objectstring celebrity;
instream.open("c:/myfile.dat");getline(instream,celebrity);cout << celebrity << endl;getline(instream,celebrity);cout << celebrity << endl;getline(instream,celebrity);cout << celebrity << endl;getline(instream,celebrity);cout << celebrity << endl;instream.close();
}Code Verified 05/12/2003
Albert EinsteinMichael FaradayAlexander Graham BellJimi Hendrix
4623/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Setting up C++ Stream I/ODefining 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.
2006 C++ Course Handouts January 2006
Notes: 232
4633/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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 outputdataFile << "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 readinggetline(dataFile, buffer); // Get first linecout << buffer << endl; // Output first linegetline(dataFile, buffer); // Get second linecout << buffer << endl; // Output second linedataFile.close();
}
4643/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Copying a Portion of a File#include <fstream>#include <string>using namespace std;
void main(void){
int i;string record_in;ifstream file_in;ofstream file_out;file_in.clear(); // clears all error codesfile_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();file_out.close();
}
Example reading a file in and writing it out.
Code verified 11/23/02
2006 C++ Course Handouts January 2006
Notes: 233
4653/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
File Open Short CutInput 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;
4663/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
C++ Stream I/OVariations 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);
2006 C++ Course Handouts January 2006
Notes: 234
4673/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Mode FlagsThe 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 operationfails. 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).
4683/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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();
}
2006 C++ Course Handouts January 2006
Notes: 235
4693/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);
4703/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Other I/O Functions
Error Processing FunctionsUse these member functions to test for errors while writing to a stream:
Function Return valuebad() 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
2006 C++ Course Handouts January 2006
Notes: 236
4713/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);}
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();
}
Code Verified 11/23/02
4723/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
good() and append Examplestring 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 filenumbers_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 appendnumbers_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 datawhile (! numbers_in.eof())
{numbers_in >> num;numbers_out << num << endl;cout << setw(8) << num << setw(3) << numbers_in.rdstate() << endl;}
// Close the filesnumbers_in.close();numbers_out.close();
}
Code Verified 11/23/02
2006 C++ Course Handouts January 2006
Notes: 237
4733/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
eof() Example#include <stdlib.h>#include <iomanip>#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();}
}
Code Verified 11/23/2002
4743/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Open Modesifstream( 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)
2006 C++ Course Handouts January 2006
Notes: 238
4753/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Example of a Seed Readvoid main(){
//declare and initialize variableshort score = 0;short numScores = 0; //countershort totalScores = 0; //accumulatorfloat average = (float) 0.0;
//open input fileifstream inFile;inFile.open("scores.dat", ios::in | ios::nocreate);
//verify that open was successfulif (!inFile.fail()) //if open did not fail{
//read test scoreinFile >> score; // Seed Readwhile (!inFile.eof())
{
//update counter and accumulatornumScores = numScores + 1;totalScores = totalScores + score;inFile >> score;}
//close fileinFile.close();
//calculate and display average test scoreaverage = (float) totalScores / (float) numScores;cout << "Average test score: " << average << endl;
}else //open failed
cout << "Error opening file." << endl;} //end of main function
4763/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 ifstreamcout belongs to ostream, NOT ofstream
2006 C++ Course Handouts January 2006
Notes: 239
4773/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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);}
fin.close();fout.close();}
Code Verified 5/30/01
4783/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
The ignore() Functionfin.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
2006 C++ Course Handouts January 2006
Notes: 240
4793/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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( );
}
4803/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 readwhile (! 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 whilecout << " Pound Signs:" << pounds << endl;cout << " Semicolons:" << semicolons << endl;cout << "Tab Characters:" << tabs << endl;
}
Example - Editing a File of Text
2006 C++ Course Handouts January 2006
Notes: 241
4813/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Basic Flow When Using Files
4823/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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 attributesios::fixed // don’t use scientific notationios::scientific // use scientific notationios::showpoint // always show a decimal pointios::showpos // show a plus on positiveios::right // right justifyios::left // left justify
2006 C++ Course Handouts January 2006
Notes: 242
4833/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
I/O Manipulators
Placed after the << operatordecendlfixedfflushhexoctrightscientificsetfill(ch)setprecision(n)setw(n)showpointnoshowpointshoposnoshowpos
4843/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Write Method
Using write()Syntax: oblect.write(variable, length);
#include <iostream>#include <string>using namespace std;void main () {
char One[] = "One if by land";
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";
}
OutputOne if by landOne ifOne
2006 C++ Course Handouts January 2006
Notes: 243
4853/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Random Access Files
#include <iostream>#include <fstream>using namespace std;
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;
}
seekg is Seek Get
seekp is seek Put
4863/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Random Access Files (1 of 3)
#include <iostream>#include <fstream>using namespace std;#include "reinterpret.h"
// Declare a structure for the recordstruct Info{
char name[51];int age;char address1[51];char address2[51];char phone[14];
};
// Function Prototypeslong byteNum(int);void showRec(Info);
2006 C++ Course Handouts January 2006
Notes: 244
4873/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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();
}
4883/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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;
}
2006 C++ Course Handouts January 2006
Notes: 245
4893/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
sprintf() .. way coolSame as printf except output is directed into a stringSyntax: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 stringsprintf(num,”%12.2f”, double_num);
4903/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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
2006 C++ Course Handouts January 2006
Notes: 246
4913/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Conversion Specification Modifiers
Format: %xywhere x is a modifier or flagand 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
4923/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
sprinf can be used to convert Binary to ASCII#include <iostream>#include <string>
using namespace std;float cost;char str[10];int length1, length2;
void main (){
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;
}
Verified 10/29/2002
1243.22length of cost is 4length of str is 7
2006 C++ Course Handouts January 2006
Notes: 247
4933/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Strstream – Writes to Memory
#include <iostream>#include <strstream>#include <iomanip>using namespace std;
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 bufferoutStr.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
Generated Output:1.0 4.0 9.0 16.0 25.0
4943/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
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?
2006 C++ Course Handouts January 2006
Notes: 248
4953/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Homework1. Should have read Chapters 1 through 10 , 12 13 by now2. Work on your term paper3. Work on Homework Packets
4963/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Chapter 13 Summary
I/O Streams Summary
Stream I/OCharacter I/Ofail()good()eof()sprintf()Manipulatorssetf()
2006 C++ Course Handouts January 2006
Notes: 249
4973/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Additional C++ Topics
Advanced Topics
Bitwise OperatorsBit FieldsC-Style File I/O OperationsRecursionPointersI/O Redirection
4983/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Interesting FactsMost Computers, Intel, Motorola or anything elseuse 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
2006 C++ Course Handouts January 2006
Notes: 250
4993/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Boolean Operations
AND OperationOR OperationXOR OperationOne’s Complement OperationLeft ShiftRight Shift
5003/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bitwise Operations
Key to success
AND means multiplyOR means add
2006 C++ Course Handouts January 2006
Notes: 251
5013/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bitwise AND Operation
00101011 4310101010 17000101010 42 Remember to multiply
Why would we want to do this ?Convert to upper or lower case
01001101 Upper case M 7701101101 Lower case m 109
01101101 Lower case m 10911011111 Mask of 223 22301001101 Result is upper case M
Of course, we could have used toupper(‘m’);
5023/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bitwise AND Operation#include <iostream.h>#include <iomanip.h>
unsigned val=109;unsigned mask=223; // Bitwise AND Operationunsigned 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
2006 C++ Course Handouts January 2006
Notes: 252
5033/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bitwise OR Operation
00101011 4310101010 17010101011 171 Remember we’re adding, now
Why would we want to do this ?Encoding / Decoding AlgorithmsCommunications Error Checking (CRC)Manipulating TCP/IP packet addressesSub-net masks on Internet firewalls (198.200.78.41)Display Graphics ManipulationsMaster Bit NotationFile Allocation Tables on some machines
262,000 tracks, 1 bit for each track=32750 bytes7168 bytes/track uses 5 tracks for MBT
5043/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bitwise OR Operation#include <iostream.h>#include <iomanip.h>
unsigned val=43;unsigned mask=170; // Bitwise OR Operationunsigned newval;
main(){
newval = val | mask;cout << setw(4) << val << setw(4) << mask << setw(4) << newval;return(0);}
Prints: 43 170 171
2006 C++ Course Handouts January 2006
Notes: 253
5053/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bitwise XOR Operation
Exclusive OR (one or the other but not both)
00101011 4310101010 17010000001 129 Remember we’re adding, Again
5063/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Bitwise XOR Operation#include <iostream.h>#include <iomanip.h>
unsigned val=43;unsigned mask=170; // Bitwise XOR Operationunsigned newval;
main(){newval = val ^ mask;cout << setw(4) << val << setw(4) << mask << setw(4) << newval;return(0);}
Prints: 43 170 129
2006 C++ Course Handouts January 2006
Notes: 254
5073/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Complement Operation
Inverse function flips each bit (bitwise negation)
00101011 4311010100 212
11111111 25500000000 0
Why would we want to do this ?Encoding / Decoding AlgorithmsCommunications Error Checking (CRC)Manipulating TCP/IP packet addressesSub-net masks on Internet firewalls (198.200.78.41)Display Graphics Manipulations
5083/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Shifting Operations
Basics of the right shift
01011100 9200101110 4600010111 2300001011 1100000101 500000010 200000001 1
Notice it is a divide by two operation
2006 C++ Course Handouts January 2006
Notes: 255
5093/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Shifting Operations
Basics of the left shift
01011100 9210111000 18401110000 11211100000 22411000000 19210000000 128
Notice it is a multiply by two operation
5103/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Shifting Example#include <iostream.h>#include <iomanip.h>unsigned val=92;int i;
main(){
for (i=0; i<9; i++){cout << setw(8) << val << endl;val = val << 1;}
return(0);}
Prints:92 184 368 736 46 23
Prints:92
1843687361472294458881177623552
2006 C++ Course Handouts January 2006
Notes: 256
5113/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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:
6000 00477748 Verified 11/27/2003
5123/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
C++ Pointers#include <iostream>using namespace std;
double d1;double d2;int x;int *iptr;double *dptr1;double *dptr2;
void main(void){
x = 100; iptr = &x; dptr1 = &d1;dptr2 = &d2;
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;
}
Address of x: 00477738Address of iptr: 0047773CContents of iptr: 00477738
Value of x: 100Contents of dptr1: 00477750Contents of dptr2: 00477758
Verified 11/27/2003
Notice the length of the double is obviously 8 bytes based on the difference in the addresses
2006 C++ Course Handouts January 2006
Notes: 257
5133/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Register class
#include <stdio.h> register x=0, var=0; // register classint y=0, count=0; // signed integers
int main(void){
for (x=0; x<10000; x++)count++;
for (y=0; y<10000; y++)count++;
.
.return(0);}
Notes: Uses very fast registers compared to memory
Register access 2 cycles
Memory access 12 cycles
Each cycle is one tick of the clock.
5143/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Register class
Register access 1 to 2 cyclesMemory access 12 to 20 cycles
10 to 12 times slower than register accessDisk 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
2006 C++ Course Handouts January 2006
Notes: 258
5153/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Generated Internal Code
Typical increment structure
loop: mov ax,count ; get initial valueinc ax ; increment registermov count,ax ; replace itmov dx,y ; load y into dxinc dx ; increment registermov y,dx ; store it backcmp dx,10000 ; test for exitjle loop ; play it again, Sam
Some machines have memory increment instructions, but, register operations are still faster than memory to memory instructions.
5163/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Generated Internal Code
Register class increment structure
clr ax ; clear ax registerclr dx ; clear dx register
loop: inc dx ; increment registerinc ax ; increment registercmp ax,10000 ; test for exitjle loop ; do it again
Six lines of code -- faster than the previous 8
2006 C++ Course Handouts January 2006
Notes: 259
5173/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 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.
5183/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
volatile Type Qualifier
Program A Program B Program C
volatile int counter
counter++ counter++ counter++
2006 C++ Course Handouts January 2006
Notes: 260
5193/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006
Summary
Summary of Boolean Operations, Hex, Binary, Octal
Boolean ExpressionsEnumeration TypesBitwise OperatorsRegister ClassVolatile & Extern