Escolar Documentos
Profissional Documentos
Cultura Documentos
CIS162
CSC100
Version 17
2006
Notes: 1
2006 C++ Course Handouts January 2006
Subject Overview
C++ Programming.
This course includes features to construct C++ programs and
functions. Topics discussed will be data types, functions, pointers,
input/output routines, structures and disk access routines. Also
discussed are inheritance, encapsulation, classes, members and
overloading. Prerequisites: CIS152 or CIS155 or CIS156 or CIS157
or CIS158 or CIS102.
Course Objectives
1. Explain the history of C++ and basic computer components
2. Describe the software development process
3. Use predefined data types to declare and manipulate variables and
arrays
4. Use operators in arithmetic and Boolean expressions
5. Design and develop structured/modular programs using various flow
control structures and functions
6. Describe object-oriented concepts
7. Design and develop programs using classes and object-oriented
programming techniques
8. Process keyboard input and console output
9. Debug simple and complex programming errors
10. Use standard preprocessor commands
11. Understand the concepts used in the construction of C++ programs,
12. Understand and implement most C++ functions
13. Understand basic structured programming concepts
14. Understand encapsulation, inheritance, scope and overloading
15. Improve your critical thinking skills
16. Understand the relationship between high-level, low-level and
machine languages
17. Understand bit-wise manipulation of data
18. Understand data conversions from binary, decimal and hexidecimal
Notes: 2
2006 C++ Course Handouts January 2006
An Excellent Text
Starting out with C++,
Alternate Version
4th Edition.
Tony Gaddis, Judy Walters
and Godfrey Muganda
Grading Policy
100% - 90% A
89% - 80% B
79% - 70% C
69% - 60% D
Below 60 Ooops
Grading Policy
Assignments are presented with the intent of reinforcing the
reading material and topics discussed in the classroom.
Late assignments are welcome, but receive a 10 percent
reduction for each week they are late. All external class
assignments are expected to be typed.
Notes: 3
2006 C++ Course Handouts January 2006
Student Deliverables
Assignment or Activity Percent
Homework 32% (32 x 1 % each)
Midterm Exam 24 %
Final Celebration 24 %
Critical Thinking Paper 5%
Quiz-1 6%
Quiz-2 6%
Attendance 3%
Total 100 %
Extra Credit Papers 5%
All sorts of ways to get an “A”
Total .8823
Extra Credit Paper 5% x 90% = .0450
Grand Total .9273 (92.73%)
Example-1
Notes: 4
2006 C++ Course Handouts January 2006
Total .8436
Extra Credit Paper 5% x 90% = .0450
Grand Total .8886 (88.86%)
Example-2
Notes: 5
2006 C++ Course Handouts January 2006
College Calendar
Notes: 6
2006 C++ Course Handouts January 2006
Class Structure
Structure of the Class
Discussions Each Class Night
¾ Roughly 2 hours per night of discussion /dialog
¾ 32 Programming Exercises
Notes: 7
2006 C++ Course Handouts January 2006
¾ or
Term Paper
Cover Page 5%
References 5%
Grammar 5%
Spelling 5%
Length 5%
Margins 5%
Page Numbers, Dates, Headings 5%
Content 65%
Notes: 8
2006 C++ Course Handouts January 2006
Teaching Philosophy
How We Learn
We will proceed through many different learning methods
¾ Lectures
¾ Dialogs
¾ Discussions
¾ Presentations
¾ Student Teach-Back
¾ Group Collaboration
¾ Writing
¾ Debates
¾ Practice by Doing C++ in Class
¾ Practice by Doing C++ at Home
¾ Email Activities
¾ Researching Topics
¾ Have Some Fun, too
Notes: 9
2006 C++ Course Handouts January 2006
Notes: 10
2006 C++ Course Handouts January 2006
Leaning Center
Plagiarism
Notes: 11
2006 C++ Course Handouts January 2006
Web Page
URL is:
www.softwaredynamix.com/javashop/index.php
Contains lots of C++ related information
Syllabus and Course Objectives
Online Midterm and Final Exams
Sample C++ Code
Homework Problems
Contact Information
Previous Test Scores
Notes: 12
2006 C++ Course Handouts January 2006
1. Name
2. Phone
3. Email Address
4. Where You Work
5. Hobbies or Interests
Syllabus Summary
Text Books
Homework & Lab Time
Attendance
Class Structure
Grading
C++ Compilers
Instructor Contact Information
Upon completion of this course, you will have
a crisp outlook and keen understanding of the
computer language of choice in today’s world
of computer science
Sound Exciting? Let’s Learn C++…
Notes: 13
2006 C++ Course Handouts January 2006
Chapter 1
Notes: 14
2006 C++ Course Handouts January 2006
Computer Systems
Computer Systems
Bus
Output
ALU Main
Memory
Primary Storage
Hardware Disk
Secondary
Registers Storage
Notes: 15
2006 C++ Course Handouts January 2006
Base Address,
say, 8000 Relative Address
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D
E a c h b y t e h a s
Units of Measure
Notes: 16
2006 C++ Course Handouts January 2006
Notes: 17
2006 C++ Course Handouts January 2006
Programmer oriented
¾ Access to memory locations
¾ Bit manipulations
¾ Character oriented
Notes: 18
2006 C++ Course Handouts January 2006
Define objectives
Preliminary design (Flow Chart Perhaps)
Write the code (Implies some kind of editor)
Compile & link
Run the program Process O nline
D isplay
Off-Page
Input Connect Predefine
Output or d Process
Notes: 19
2006 C++ Course Handouts January 2006
Flowcharting
Start
Print
Byte
No
EOF
Yes
Close
File Stop
Notes: 20
2006 C++ Course Handouts January 2006
Preliminary Investigation
Maintenance
Systems Analysis
Systems Development
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 41
Notes: 21
2006 C++ Course Handouts January 2006
Desk checking
Manual testing with sample data
Quality assurance (QA)
Walk through
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 43
Algorithms
Like a recipe
Same as
¾ Directions
¾ Methods
¾ Procedures
An algorithm is a sequence of precise instructions
that leads to a solution
We’ll use the word “algorithm” a lot in this class
Sorting, searching, etc
Payroll applications have many algorithms,
¾ Bonus calculations, pay calculations, tax calculations
Notes: 22
2006 C++ Course Handouts January 2006
Chapter 1 Summary
Chapter 2
Introduction to C++
Variables
Assignment Statements
Declarations
cout
#include directives
Escape Sequences
Data Types
Arithmetic Operators
Simple Flow Control
Programming Style
Notes: 23
2006 C++ Course Handouts January 2006
What is Binary?
11111111 255
Mechanics of Binary?
Notes: 24
2006 C++ Course Handouts January 2006
Notes: 25
2006 C++ Course Handouts January 2006
#include <iostream>
using namespace std;
main()
{
cout << “This is a simple C++ Program “ << endl;
}
Notes: 26
2006 C++ Course Handouts January 2006
#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;
int main()
{
variable declarations
Main Body
C++ statements
return(0);
}
Return statement
Notes: 27
2006 C++ Course Handouts January 2006
Use of Semicolons
int x = 100;
cost = 100.99;
cout << “This is C++ at its finest \n”;
display_text(x);
return(0);
printf(“C++ is Very Cool..”);
Code Blocks
Braces
{
Marks the begin and end of
a block of code
}
White Space
Notes: 28
2006 C++ Course Handouts January 2006
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 57
Notes: 29
2006 C++ Course Handouts January 2006
Compilers
User types in
C++ Source
Code
Notes: 30
2006 C++ Course Handouts January 2006
Notes: 31
2006 C++ Course Handouts January 2006
Questions
1. Who can discuss the difference
between a keyword and a variable?
2. What is a C++ Comment?
C++ Keywords
1. asm 21. for 41.struct
2. auto 22. friend 42.switch
3. break 23. goto 43.template
4. bool 24. if 44.this
5. case 25. inline 45.throw
6. catch 26. int 46.true
7. char 27. long 47.try
8. class 28. mutable 48.typedef
9. const 29. namespace 49.typeid
10. continue 30. new 50.typename
11. default 31. operator 51.union
12. delete 32. private 52.unsigned
13. do 33. protected 53.using
14. double 34. public 54.virtual
15. else 35. register 55.void
16. enum 36. return 56.volatile
17. extern 37. short 57.while
18. explicit 38. signed
19. false 39. sizeof
20. float 40. static
Notes: 32
2006 C++ Course Handouts January 2006
Tokens
int counter=0;
counter++;
Notes: 33
2006 C++ Course Handouts January 2006
Comments in C++
// C++ Comments
// Continue until the end of line
// ;-------------------------------------
// ; Comments about a section of code
// ;-------------------------------------
x = q;
y= x / 12.2 * (x * 1.223);
/* standard C comment text */
/* ;-------------------------------------
; Comments about a section of code
;------------------------------------- */
x = q;
Y = x / 12.2 * (x * 1.223);
Notes: 34
2006 C++ Course Handouts January 2006
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 ;
// ;----------------------------------------------------------;
What Is a Variable
Notes: 35
2006 C++ Course Handouts January 2006
What Is a Variable
A Variable is place in computer memory where we
store information used in our programs.
Each data variable has three components
¾ Its Name,
¾ Its Value,
¾ Its Type
Variable Declaration
All variables must be declared before they are used
Syntax
Type_Name Variable_Name_1, Variable_Name_2, Variable_Name_n;
Type_Name Variable_Name=initial_value;
Type_Name Variable_Name(initial value);
Examples
int result,
count,
age,
length,
myVariable;
int accum=0;
int counter(0);
char StatusByte;
float cost_of_goods_sold;
double national_debt=0.0;
bool complete;
Notes: 36
2006 C++ Course Handouts January 2006
Variable Declaration
Variable Declaration
Each variable takes a certain amount of memory space
depending on the type of compiler
Notes: 37
2006 C++ Course Handouts January 2006
Variable Declaration
x = y * z;
Notes: 38
2006 C++ Course Handouts January 2006
Notes: 39
2006 C++ Course Handouts January 2006
Data Types
Notes: 40
2006 C++ Course Handouts January 2006
Data Types
Notes: 41
2006 C++ Course Handouts January 2006
Sign Bit
Signed means you can have both positive and
negative values. The high-order bit, the sign bit, is
used to denote negativity.
Unsigned means you can store only positive values.
The sign bit is used for data not a sign.
Size of an Integer
Size of Integers
On any one computer, each variable type takes up a
single unchanging amount of room. That is, an integer
might be two bytes on one machine, and four on another,
but on either computer it is always the same, day in and
day out.
A char variable (used to hold characters) is most often
one byte long. A short integer is two bytes on most
computers, a long integer is usually four bytes, and an
integer (without the keyword short or long) can be two
or four bytes.
A character is a single letter, number or symbol that
takes up one byte of memory.
Notes: 42
2006 C++ Course Handouts January 2006
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";
}
Notes: 43
2006 C++ Course Handouts January 2006
Break
Notes: 44
2006 C++ Course Handouts January 2006
Same as
char myName[30];
char yourName[30]; An Array of
char bookTitle[45]; Characters
char Inventory_Item_Description[60];
Notes: 45
2006 C++ Course Handouts January 2006
void main()
Generated Output
{ Ada Lovelace
string myName; Sally Ride
string yourName; Ada LovelaceSally Ride
string bothNames;
Notes: 46
2006 C++ Course Handouts January 2006
float 4 bytes
double 8 bytes
long double 8 bytes. Some use 10 or 16 bytes
Notes: 47
2006 C++ Course Handouts January 2006
are_we_finished = false;
cout << are_we_finished << "\n\n";
are_we_finished = true;
cout << are_we_finished << "\n\n";
}
Notes: 48
2006 C++ Course Handouts January 2006
Equivalents
Simple Arrays
Notes: 49
2006 C++ Course Handouts January 2006
int x = 100;
char ch = ‘A’;
char name[4] = “TEST“;
short int counter = 1;
100 A T E S T 1
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 100
Notes: 50
2006 C++ Course Handouts January 2006
ASCII v. Numeric
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 101
Assignment Statements
Syntax:
Variable = Expression
Simple Examples:
x = 1;
a = x * 100;
b = 0;
ch = ‘A’;
z = (d/2) + 40;
cost = 154.90;
mass = 300000;
Distance_to_Moon = 210000;
counter = counter + 1;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 102
Notes: 51
2006 C++ Course Handouts January 2006
Assignment Statements
int main()
{
x = 1; Initialized at run time
count = 0;
mass = 0.0;
cost = 0.0;
ch = ' ';
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 103
Assignment Statements
Multiple Assignments
An unusual feature of C++ is the fact that an
assignment statement also has a value.
The value of the assignment statement can
itself be assigned to another variable. For
example, the statement a = 77 has a value
of 77. So we can have
b = a = 77; // both variables take the value 77
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 104
Notes: 52
2006 C++ Course Handouts January 2006
#include <iostream>
using namespace std;
Or
#include <iostream.h>
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 105
Syntax
cout << variable-1 << variable-2 << text-1 << text-2;
Examples
int input_number=1000;
cout << “Enter a number less than 100”;
cout << “Number entered is ” << input_number << endl;
cout << “Press Enter \n”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 106
Notes: 53
2006 C++ Course Handouts January 2006
Examples
cout << “This is a test”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 107
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 108
Notes: 54
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 109
Examples:
#define PI 3.14159
#define GRAVITY 32.2
#define LF 10
#define CR 13
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 110
Notes: 55
2006 C++ Course Handouts January 2006
void main(void)
{
circumference = diameter * PI;
cout << "Circumference is " << circumference << endl;
cout << "Where Pi is "
<< PI
<< " and diameter is "
<< diameter
<< endl;
cout << MAX;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 111
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 112
Notes: 56
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 113
Chapter 2 Summary
Introduction to C++
Variables
Assignment Statement
Declarations
cout
Escape Sequences
Formatting Numbers
Data Types
Various Operators
Programming Style
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 114
Notes: 57
2006 C++ Course Handouts January 2006
Chapter 3
Cin
I/O Manipulators
Printing Hex and Octal
Operators
Expressions
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 115
cin Object
Examples
cin >> number1;
cin >> mass_of_sun >> distance_from_earth;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 116
Notes: 58
2006 C++ Course Handouts January 2006
cin Object
#include <iostream>
using namespace std;
void main()
{
Enter an integer, a float and a character:
1234 1234.456 B
int whole; Whole Number is:1234
float fraction; Fractional Number is:1234.46
char letter; Letter Entered is: B
cout << " Whole Number is:" << whole << endl;
cout << "Fractional Number is:" << fraction << endl;
cout << " Letter Entered is:" << letter << endl;
} // end of main
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 117
void main()
{ Member
char fullname[50]; Function
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 118
Notes: 59
2006 C++ Course Handouts January 2006
void main()
{
string st;
Samuel F. B. Morse
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 119
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 120
Notes: 60
2006 C++ Course Handouts January 2006
I/O Manipulators
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(4);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 121
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 122
Notes: 61
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 123
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 124
Notes: 62
2006 C++ Course Handouts January 2006
void main ()
{
cout.setf ( ios_base::hex, ios_base::basefield ); // set hex as the basefield
cout.setf ( ios_base::showbase ); // activate showbase
cout << 700 << endl;
cout << 255 << endl; Output
cout.unsetf ( ios_base::hex ); // deactivate hex 0x2bc
cout.setf ( ios_base::oct ); // activate octal 0xff
cout << 700 << endl;
cout << 255 << endl;
01274
0377
cout.unsetf ( ios_base::oct ); // deactivate hex
cout.unsetf ( ios_base::showbase ); // deactivate showbase 700
cout << 700 << endl;
cout << 255 << endl; 255
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 125
setprecision() Example
#include <iostream> 1234.123400
#include <iomanip> 1234.12340
using namespace std; 1234.1234
1234.123
void main() 1234.12
{ 1234.1
double cost=1234.1234; 1234
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 126
Notes: 63
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 127
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 128
Notes: 64
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 129
void main()
{
double x;
double y;
double value;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 130
Notes: 65
2006 C++ Course Handouts January 2006
sizeof() Operator
sizeof() operator
Used to obtain the size of any particular data type
Examples:
#include <iostream>
Size of an Integer is: 2
using namespace std;
Size of a Long is: 4
void main() Size of a Short is: 1
{ Size of a Float is: 4
int s; Size of a Double is: 8
char ch; Size of a char is: 1
float cost_of_goods;
double mass_of_the_earth;
long distance;
s = sizeof(float);
cout << "Size of an Integer is: “ << sizeof(int) << endl;
cout << " Size of a Long is: “ << sizeof(distance) << endl;
cout << " Size of a Short is: “ << sizeof(short) << endl;
cout << " Size of a Float is: “ << sizeof(cost_of_goods)<< endl;
cout << " Size of a Double is: “ << sizeof(double) << endl;
cout << " Size of a char is: “ << sizeof(char) << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 131
Operator Precedence
( ) Parentheses
- + ++ -- Unary Operators
* / % Multiply, Divide, Modulo
+ - Plus, Minus
< > <= >= Greater-Than, Less-Than
== != Equal to, Not Equal to
&& And
|| Or
= Set
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 132
Notes: 66
2006 C++ Course Handouts January 2006
A word of Caution
butter = 25.0 + 60.0 * n / scale;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 133
Mathematical Expressions
Y = 3X
2
Y = (3 * X) / 2;
Y = (X / 2) * 3;
Y = (3 / 2) * X;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 134
Notes: 67
2006 C++ Course Handouts January 2006
Exponents in C++
y = 9x3+25
y = (9 * pow(x,3)) + 25;
y = (9x3)5
y = pow((9 * pow(x,3)),5);
Exponent Function
y=pow(n, q); // n raised to the power of q
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 135
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 136
Notes: 68
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 137
strlen() Function
strlen() operator
Used to obtain the size of a string’s contents
#include <iostream>
using namespace std;
void main()
{ Santa Claus
int len; Content Length:11
char myName[30]; String Capacity:30
strcpy(myName, "Santa Claus");
len=strlen(myName);
cout << myName << endl;
cout << " Content Length:" << len << endl;
cout << "String Capacity:" << sizeof(myName) << endl;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 138
Notes: 69
2006 C++ Course Handouts January 2006
Symbolic Constants
float x = 100.00;
const float PI = 3.14159;
const float SQUARE_ROOT_OF_2 = 1.4142;
int main(void)
{
x = 3 / SQUARE_ROOT_OF_2; // Okay
PI = 3.2; // Not gonna happen
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 139
Literal Constants
Floating Point
Integer
Character
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 140
Notes: 70
2006 C++ Course Handouts January 2006
15.75 // 15.75
1.575E1 // 15.75
1575E-2 // 15.75
-2.5e-3 // -0.0025
25e-4 // 0.0025
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 141
Integer Constants
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 142
Notes: 71
2006 C++ Course Handouts January 2006
Numeric Constants
Integer constants can be decimal, octal or hexidecimal.
(base 10, 8 & 16)
// Decimal Constants (Base 10)
10
132
32179
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 143
Character Constants
Used for letters of the alphabet, special characters, etc.
Wrapped in single quotes: ‘a’ ‘B’
Can be escape characters: ‘\n’ ‘\a’
Can be hex or octal escape sequence: ‘\x07’
Examples:
char ch = 'Q';
char_code = '$';
ch = ‘t’;
ch = 116;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 144
Notes: 72
2006 C++ Course Handouts January 2006
Operators
= Assignment ++ Auto Increment
< less than -- Auto Decrement
<= less than or equal += Increment
== equal to -= Subtract
> greater than *= Multiply
>= greater than or equal /= Divide
!= NOT equal to %= Modulo
~ Compliment % Modulo
| Boolean Or + Add
& Boolean And - Subtract
^ Exclusive Or * Multiply
>> Shift right / Division
<< Shift Left . Dot Operator
&& Logical And :: Scope Resolution
|| Logical Or
! Not Operator
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 145
Incrementing A Variable
The most common value to add (or subtract) and then
reassign into a variable is 1. In C++, increasing a
value by 1 is called incrementing, and decreasing by
1 is called decrementing. There are special operators
to perform these actions
Say we have,
int x=0;
Increment
x=x+1; // Traditional
x+=1; // shorthand for x=x+1
x++; // postfix mode, same as x=x+1
++x; // prefix mode, same as x=x+1
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 146
Notes: 73
2006 C++ Course Handouts January 2006
Decrementing a Variable
The most common value to add (or subtract) and then
reassign into a variable is 1. In C++, increasing a
value by 1 is called incrementing, and decreasing by
1 is called decrementing. There are special operators
to perform these actions
Say we have,
int x=10;
Decrement
x=x-1; // Traditional
x-=1; // shorthand for x=x-1
x--; // postfix mode, same as x=x-1
--x; // prefix mode, same as x=x-1
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 147
Say we have,
int x = 10;
Increment
x=x+5; // Traditional
x+=5; // shorthand for x=x+5
Decrement
x=x-5; // Traditional
x-=5; // shorthand for x=x-5
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 148
Notes: 74
2006 C++ Course Handouts January 2006
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;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 149
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 150
Notes: 75
2006 C++ Course Handouts January 2006
Type Casting
Sometimes you need to use type casts to tell the compiler to
convert the type of an expression to another type.
For example, suppose that you have the sum of integer values
in an integer variable, and would like to compute the average
and store it in a variable of type float.
In this case, you must tell the compiler to first convert sum to
float before performing the division.
// Older C-style of type casting
int sum, n;
float average;
average = (float) sum / n;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 151
Type Casting
The Type Cast Operator
int total=0;
float x=1.6;
float y=1.7;
total = x + y;
If 1.6 + 1.7 = 3.3, then why does total = 3?
total = (int) x + (int) y;
result: total equals 2
because 1.6 converts to integer 1
and 1.7 converts to integer 1
Conversion is done before the addition operation
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 152
Notes: 76
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 153
Modulus Arithmetic
int x, y, z;
x = 13;
y = 3;
z = x % y; // z will have 1, not 4.3333
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 154
Notes: 77
2006 C++ Course Handouts January 2006
Modulus Operator
Modulus Operator: %
The result of the modulus operator (%) is the remainder when the first
operand is divided by the second.
Example
if ((nCenturyYear % 4) == 0) {
LeapYearFunction();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 155
int main( )
{ Large loop with a display every 10,000
long x;
long rem;
char ch;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 156
Notes: 78
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 157
Homework
1. Should have read Chapters 1 and 2 by now
2. Read Chapter 3 for next week
3. Work on your term paper
4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 4 on page 161 of the text.
(Chapter 3)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 158
Notes: 79
2006 C++ Course Handouts January 2006
Chapter 3 Summary
Introduction to C++
Variables
Assignment Statement
Declarations
cin
Escape Sequences
Formatting Numbers
Data Types
Various Operators
Programming Style
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 159
Chapter 4
If Statement
If -- Else
Switch Statement
Logical Operators
Expressions
Enumerated Types
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 160
Notes: 80
2006 C++ Course Handouts January 2006
Insight
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 161
Logical Operators
Logical Operators
&& And
|| Or
! Not
Produces one of two values, TRUE or FALSE
==
!=
<
<=
>
>= Operate on pairs of built in types
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 162
Notes: 81
2006 C++ Course Handouts January 2006
Expression Examples
if (x < 100)
if (x > 0)
if (count <= 50)
if (count >= 1000)
if (ch != ‘Z’)
if (status == 1)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 163
If Statement Syntax
Syntax
if (expression)
C++ statement
if (expression)
{
C++ statements
C++ statements
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 164
Notes: 82
2006 C++ Course Handouts January 2006
if statement
Example
int main(void)
{
float cost;
cout << "Enter Product Cost Less than $100.00: ";
cin >> cost;
if (cost > 100.00)
cout << "Cost Entered Exceeded $100.00 " << cost << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 165
int number_in;
int max=0;
int min = 999999;
cout << "Enter a floating point number:";
cin >> number_in;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 166
Notes: 83
2006 C++ Course Handouts January 2006
If - else
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 167
cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;
if (testScore < 60) Enter your test score and I will tell you
grade = 'F'; the letter grade you earned: 44
if (testScore < 70) Your grade is A.
grade = 'D';
if (testScore < 80)
grade = 'C';
if (testScore < 90)
grade = 'B';
if (testScore <= 100)
grade = 'A'; Verified 11/23/2003
Notes: 84
2006 C++ Course Handouts January 2006
cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;
if (testScore <= 100) Enter your test score and I will tell you
grade = 'A'; the letter grade you earned: 44
if (testScore < 90) Your grade is F.
grade = 'B';
if (testScore < 80)
grade = 'C';
if (testScore < 70)
grade = 'D';
if (testScore < 60)
grade = 'F'; Verified 11/23/2003
else if construct
#include <iostream>
using namespace std;
int main()
{ Or, we can use the else-if
int testScore; construct
char grade;
bool goodScore = true;
if (goodScore)
cout << "Your grade is " << grade << ".\n"; Verified 11/23/2003
else
cout << testScore << " is an invalid score.\n";
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 170
Notes: 85
2006 C++ Course Handouts January 2006
Else-if Example (1 of 2)
void main()
{
char choice;
int months;
float charges;
cout << " Health Club Membership Menu\n";
cout << "A. Standard Adult Membership\n";
cout << "B. Child Membership\n";
cout << "C. Senior Citizen Membership\n";
cout << "D. Quit the Program\n\n";
cout << "Enter your choice: ";
cin.get(choice);
Continued
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 171
Else-if Example (2 of 2)
if (choice < 'A' || choice > 'D')
{ cout << "The valid choices are A through D.\n";
cout << "Run the program again\n";
}
else if (choice == 'A')
{ cout << "For how many months? ";
cin >> months;
charges = months * 40.00;
cout << "The total charges are $" << charges << endl;
}
else if (choice == 'B')
{ cout << "For how many months? ";
cin >> months;
charges = months * 20.00;
cout << "The total charges are $" << charges << endl;
}
else if (choice == 'C')
{ cout << "For how many months? ";
cin >> months;
charges = months * 30.00;
cout << "The total charges are $" << charges << endl;
}
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 172
Notes: 86
2006 C++ Course Handouts January 2006
Nested if statements
void main()
{
char employed, recentGrad;
if (employed == 'Y')
{ // Nested if
if (recentGrad == 'Y') // Employed and a recent grad
{
cout << "You qualify for the special interest rate.\n";
}
else // Employed but not a recent grad
{
cout << "You must have graduated from ";
cout << "college in the past two years to qualify.\n";
}
}
else // Not employed
cout << "You must be employed to qualify.\n";
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 173
Nested if statements
if (status == SINGLE)
{
if (income <= SINGLE_CUTOFF1)
tax = RATE1 * income;
else if (income <= SINGLE_CUTOFF2)
tax = SINGLE_BASE2 + RATE2 * (income - SINGLE_CUTOFF1);
else
tax = SINGLE_BASE3 + RATE3 * (income - SINGLE_CUTOFF2);
}
else
{
if (income <= MARRIED_CUTOFF1)
tax = RATE1 * income;
else if (income <= MARRIED_CUTOFF2)
tax = MARRIED_BASE2 + RATE2 * (income - MARRIED_CUTOFF1);
else
tax = MARRIED_BASE3 + RATE3 * (income - MARRIED_CUTOFF2);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 174
Notes: 87
2006 C++ Course Handouts January 2006
And operator
if (income > 100000 && dependents == 0)
tax_amount = income * 0.33;
Or operator
if (income > 200000 || itemized_deductions > 50000)
call_an_audit = true;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 175
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 176
Notes: 88
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 177
Logical Or Condition
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 178
Notes: 89
2006 C++ Course Handouts January 2006
Logical Or Condition
void main()
{ Making a previous example, better
char employed, recentGrad;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 179
((y<3) || (y>7))
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 180
Notes: 90
2006 C++ Course Handouts January 2006
void main()
{
float income;
int years;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 181
Some Rules
AND Condition
Exp-1 Exp-2 Exp1 && Exp2
True True True
True False False
False True False
False False False
OR Condition
Exp-1 Exp-2 Exp1 || Exp2
True True True
True False True
False True True
False False False
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 182
Notes: 91
2006 C++ Course Handouts January 2006
Some Rules
AND Condition (Multiply)
Exp-1 Exp-2 Exp1 && Exp2
1 1 1
1 0 0
0 1 0
0 0 0
OR Condition (Add)
Exp-1 Exp-2 Exp1 || Exp2
1 1 1
1 0 1
0 1 1
0 0 0
Think of True as 1 and False as 0
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 183
Technical Notes
Logical AND
if ( (x == 5) && (y == 5) )
if ( x == 5 && y == 5 )
Logical OR
if ( (x == 5) || (y == 5) )
if ( x == 5 || y == 5 )
Logical NOT
These are the same
if ( !(x == 5) )
if (x != 5)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 184
Notes: 92
2006 C++ Course Handouts January 2006
Tao of C++
c=10;
d=2;
x = (c > d);
y = (d == c);
b = (c < 2);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 185
if (value)
cout << “It is True”;
if (x + y)
cout << “It is True”;
if (pow(a, b))
cout << “It is True”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 186
Notes: 93
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 187
Example of TRUE/FALSE
int x, y, z;
main(void)
{
x = 10;
y = 0;
z = -12;
if (x)
cout << "X is True: " << x << endl; // Prints
else
cout << "X is False:" << x << endl;
if (y)
cout << "Y is True: " << y << endl;
else
cout << "Y is False:" << y << endl; // Prints
if (z)
cout << "Z is True: " << z << endl; // Prints
else
cout << "Z is False:" << z << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 188
Notes: 94
2006 C++ Course Handouts January 2006
Not Operator
NOT Operation
Exp !Exp
1 0
0 1
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 189
Not Operator
#include <iostream>
using namespace std;
void main()
{
float income;
int years;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 190
Notes: 95
2006 C++ Course Handouts January 2006
De Morgan’s Law
What if..
if (amount > 0 && amount < 1000) …
(A × B) = A + B
(A + B) = A × B
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 191
De Morgan’s Law
Let’s prove it:
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 192
Notes: 96
2006 C++ Course Handouts January 2006
Practice
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 193
Practice
if (x <= 3)
if (x != 2)
cout << “Hey There \n”;
else
cout << “Go Man Go \n”;
else
cout << “Here we are ! \n”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 194
Notes: 97
2006 C++ Course Handouts January 2006
Common Problem
w = 1;
if (w = 2)
cout << “w equals 2”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 195
Common Problem
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 196
Notes: 98
2006 C++ Course Handouts January 2006
Common Problem
Dangling else
if (richter_value >=0)
if (richter_value <=4)
cout << “Harmless”;
else
cout << “Negative Value is invalid”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 197
Quality Tip
if (n-- > 0)
other C++ statements
Do this instead:
d = b * b - 4 * a * c;
if (d >= 0)
r=sqrt(d);
if (n-- > 0)
other C++ statements
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 198
Notes: 99
2006 C++ Course Handouts January 2006
Switch statement
int digit;
switch (digit)
{
case 1: cout << “one”; break;
case 2: cout << “two”; break;
case 3: cout << “three”; break;
case 4: cout << “four”; break;
default: cout << “error”; break;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 199
Switch statement
#include <iostream>
using namespace std;
Code Verified 09/20/2001
int main( )
{
char grade;
cout << "Enter your midterm grade and press return: ";
cin >> grade;
switch (grade)
{
case 'A':
cout << "Excellent. "
<< "You need not take the final.\n";
break;
case 'B':
cout << "Very good. ";
cout << "Your midterm grade now is "
<< grade << endl;
break;
case 'C':
cout << "Passing.\n";
break;
case 'D':
case 'F':
cout << "Not good. “ << "Go study.\n";
break;
default:
cout << "That is not a possible grade.\n";
}
cout << "End of program.\n";
return 0;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 200
Notes: 100
2006 C++ Course Handouts January 2006
Switch Statement
#include <iostream>
using namespace std;
int main( )
{ Code Verified 09/19/2001
char ch;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 201
Code Blocks
if (day == 29)
if (month == 2)
if (year == 2000)
{
total_balance = 0.0;
inventory_quantity = 100;
cout << day << month << year;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 202
Notes: 101
2006 C++ Course Handouts January 2006
Code Blocks
if (day == 29)
if (month == 2)
if (year == 2000)
{
double Monthly_Usage;
long Julian_Date;
Monthly_Usage = consumption * 1.223;
Julian_Date = 23456;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 203
goto statement
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 204
Notes: 102
2006 C++ Course Handouts January 2006
Syntax:
expression ? Expression : expression
a = x > 100 ? 0 : 1;
Is the same as
if (x > 100)
a = 0;
else
a = 1;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 205
Syntax:
expression ? Expression : expression
score = 90;
cout << "Your Grade is " << (score<60 ? "Fail“ : "Passing");
Is the same as
if (score < 60)
cout << "Your Grade is Failing;
else
cout << "Your Grade is Passing;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 206
Notes: 103
2006 C++ Course Handouts January 2006
int main()
{
const float payRate = 50.0;
float hours, charges;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 207
Enumerated Types
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 208
Notes: 104
2006 C++ Course Handouts January 2006
Enumerated Types
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 209
void main()
{
double f= 4.35;
int n = (int)(100 * f);
if (n == 435)
cout << n << "\n";
else
cout << “Something is wrong “ << n << endl;
}
Prints
Something is wrong 434
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 210
Notes: 105
2006 C++ Course Handouts January 2006
void main()
{
double a=6 * 0.666666;
if (a == 4.0)
cout << "Hit"; // not true
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 212
Notes: 106
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 213
Artificial Intelligence
Reasoning ability
I drove the car into the garage and it died.
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 214
Notes: 107
2006 C++ Course Handouts January 2006
Review
1. The value of a relational expression is zero if the expression is
__________________?
2. What does the following code fragment print?
score = 70;
cout << "Your Grade is " <<
(score < 60 ? "Fail“ : "Passing");
3. Discuss the break statement. Where is it used?
4. Discuss the continue statement. Where is it used?
5. What will the following code fragment print?
Counter = 10;
if (Counter = 11)
cout << “Counter equals 11” << endl;
6. Say we have the following expression and y=18, q=20, evaluate
the following expression:
((y<3) || (y>17) && q == 20)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 215
Homework
1. Should have read Chapters 1 through 4 by now
2. Read Chapter 5 for next week
3. Work on your term paper
4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 4 on page 249 of the text.
(Chapter 3)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 216
Notes: 108
2006 C++ Course Handouts January 2006
Chapter 4 Summary
If Statement
If -- Else
Switch Statement
Logical Operators
Expressions
Goto Statement
Enumerated Types
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 217
Chapter 5
Looping in C++
While Loops
Do Loops
For…Next Loops
Continue Statement
Break Statement
Goto Statement
Test for Entrance Loop
Test for Exit Loop
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 218
Notes: 109
2006 C++ Course Handouts January 2006
While Loops
Basic Structure
while (expression)
C++ statement
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 219
While Loops
Single-statement body
while (Expression)
Single Statement;
Multi-statement body
while (Expression)
{
Statement-1;
Statement-2;
Statement-3;
Statement-n;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 220
Notes: 110
2006 C++ Course Handouts January 2006
void main()
{
int number;
Verified
04/24/2003
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 221
Output
void main() Enter a Character:A
{ Count:1 A
char ch; Enter a Character:B
int x; Count:2 B
x = 1; Enter a Character:C
Count:3 C
while (ch != '$') Enter a Character:W
{ Count:4 W
cout << "Enter a Character:"; Enter a Character:X
cin >> ch; Count:5 X
cout << "Count:"; Enter a Character:#
cout << x++ << " "; Count:6 #
cout << ch << endl; Enter a Character:$
} Count:7 $
}
Verified
04/24/2003
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 222
Notes: 111
2006 C++ Course Handouts January 2006
cout << "For how many days do you have sales figures? ";
cin >> days;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 223
count = 10;
while (count <= 5)
{
cout << “Current Count:” << count++ << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 224
Notes: 112
2006 C++ Course Handouts January 2006
count = 3;
while (count <= 5)
{
cout << “Current Count:” << count++ << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 225
Caution!
count = 3;
while (count <= 5)
cout << “Current Count:” << count << endl;
count++;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 226
Notes: 113
2006 C++ Course Handouts January 2006
Caution!
count = 3;
while (count = 5)
cout << “Current Count:” << count++ << endl;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 227
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 228
Notes: 114
2006 C++ Course Handouts January 2006
Do While
Two Formats for the “Do While”
do {
statement-1;
statement-2;
statement-n;
} while (Boolean Expression);
do
statement-1;
while (Boolean Expression);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 229
Do While
count = 0;
do
{
cout << “Current Count:” << count << endl;
count++;
}
while (count <= 5);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 230
Notes: 115
2006 C++ Course Handouts January 2006
Do While
#include <iostream>
using namespace std;
int main()
{
int score1, score2, score3;
float average;
char again;
do
{
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 231
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 232
Notes: 116
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 233
Void main()
{
// Establish test variables
min=9999999.99;
max=0.0;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 234
Notes: 117
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 235
For Loop
Single-statement body
for (Initialization; Boolean Test; Update Action)
Single Statement;
Multi-statement body
for (Initialization; Boolean Test; Update Action)
{
Statement-1;
Statement-2;
Statement-3;
Statement-n;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 236
Notes: 118
2006 C++ Course Handouts January 2006
For Loop
Examples
for (count=0; count<1000; count++)
{
Statement-1;
Statement-2;
Statement-n;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 237
For Loop
Examples
for (count=0; count<1000 && x>10; count++)
Statement-1;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 238
Notes: 119
2006 C++ Course Handouts January 2006
For Loop
Common Problem
for (count=0; count<1000 && x>10; count++);
Statement-1;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 239
#include <iostream>
#include <iomanip>
using namespace std;
long x,y,z;
void main ()
{
for (x=0,y=0,z=0; x<10 && y<100 || z<50; x++, y=y+10, z=z+2)
{
cout << setw(8) << x << setw(8) << y << setw(8) << z << endl;
}
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 240
Notes: 120
2006 C++ Course Handouts January 2006
void main()
{
int counter = 0;
Verified
04/24/2003
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 241
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 242
Notes: 121
2006 C++ Course Handouts January 2006
Nested Loops
#include <iostream>
using namespace std;
int x, y;
main()
{
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 243
continue statement
Code verified 6/21/01
Generated Output
Value of x is 3
Example of continue statement Value of x is 4
#include <iostream> Value of x is 5
using namespace std; Value of x is 6
Value of x is 7
int x;
Value of x is 8
int main(void) Value of x is 9
{ Value of x is 10
x = 0;
while (x < 20) Value of x is 11
{ Value of x is 12
x++;
if (x == 1 || x == 2) Value of x is 13
continue; Value of x is 14
cout << "Value of x is " << x << endl; Value of x is 15
} Value of x is 16
} Value of x is 17
Value of x is 18
Value of x is 19
Continue forces the Value of x is 20
next iteration of the
loop.
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 244
Notes: 122
2006 C++ Course Handouts January 2006
Break Statement
Example
count = 100;
while (1)
{
if (count == 0)
break;
count--;
cout << count << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 245
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 246
Notes: 123
2006 C++ Course Handouts January 2006
int number;
do
{
cout << "Enter a number between 1 and 100: ";
cin >> number;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 247
Loops in Review
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 248
Notes: 124
2006 C++ Course Handouts January 2006
Homework
1. Should have read Chapters 1 through 5 by now
2. Read Chapter 6 for next week
3. Work on your term paper
4. Classroom Group Activity: Break into groups of 2, 3 or
4 students. Do problems 9 on page 310 of the text.
(Chapter 3)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 249
Chapter 5 Summary
While loops
For loops
Do – While
Nested Loops
Test for Entrance
Test for Exit
Counters
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 250
Notes: 125
2006 C++ Course Handouts January 2006
Section 4b
Encryption Fundamentals
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 251
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.
DES 64-bit
Triple DES 128-bit
Rijndael 64-bit
RC2 64-bit
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 252
Notes: 126
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 253
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 254
Notes: 127
2006 C++ Course Handouts January 2006
Easy to crack
Linguistic patterns are obvious
E is the most common letter, followed by t, a,
o, n
T is the most common letter to begin a word
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 255
ABCDEFGHIJKLMNOPQRSTUVWXYZ
FEATHRZYXWVUSQPONMLKJIGDCB
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 256
Notes: 128
2006 C++ Course Handouts January 2006
Vigenère Cipher
Pick a word for the key, say TIGER
Use the ‘T’ as the starting offset
ABCDEFGHIJKLMNOPQRSTUVWXYZ
TUVWXYZABCDEFGHIJKLMNOPQRS
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 257
A 65 01000001
XOR 06 00000110
G 72 01000111
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 258
Notes: 129
2006 C++ Course Handouts January 2006
newchar = ch ^ key;
cout << newchar;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 259
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 260
Notes: 130
2006 C++ Course Handouts January 2006
#include <iostream>
using namespace std;
void main(void)
{
const int MAX = 24;
char product_key[MAX] ="ABCD1234-2004";
char encrypted[MAX];
char decrypted[MAX];
int length, i, key=13;
Original Message:ABCD1234-2004
for (i=0; i<MAX; i++) Encrypted:LONI<?>9 ?==9
{
encrypted[i]='\0'; Decrypted:ABCD1234-2004
decrypted[i]='\0';
}
length = strlen(product_key);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 261
http://www.cert.org/advisories/
Carnegie Melon University Software Engineering
Institute
Several hundred per year are published
It is stated that 85% of the CERT advisories could have
been prevented by using cryptography
Black-box tests, White-box tests, Red Team Testing
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 262
Notes: 131
2006 C++ Course Handouts January 2006
Encryption Summary
Summary of Encryption
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 263
Chapter 6
Functions
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 264
Notes: 132
2006 C++ Course Handouts January 2006
Functions
What is a function?
1. Who can explain what a function is in terms of
mathematics?
2. What is reusable code?
3. Why do we create and use software functions?
4. Who can describe the difference between
programmer defined and built-in functions?
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 265
Functions
What is a function?
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 266
Notes: 133
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 267
y = mx + b
Where
¾ y is the return value
¾ m, x and b are passed arguments
Arguments can be numeric, character, etc
Return values can be numeric or character
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 268
Notes: 134
2006 C++ Course Handouts January 2006
Functions - Syntax
Function Definition:
return_type function_name (arg1_type arg-1, arg2_type
arg-2, arg-n..)
{
C++ statements
.
.
return(value);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 269
Functions – 3 Parts
The Prototype:
return_type function_name(arguments);
Function Call:
receiving_variable =
function_name(arguments);
Function Definition:
return_type function_name(arguments)
{
C++ statements;
return(value);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 270
Notes: 135
2006 C++ Course Handouts January 2006
Functions - Syntax
Example showing integer return value
int result;
Prototype:
int squared(int x);
Calling a Function:
result = squared(10);
Function:
int squared(int x)
{
x=x*x;
return(x);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 271
Declaring a Function
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 272
Notes: 136
2006 C++ Course Handouts January 2006
Prototype Variations
Prototype Variations
int squared(int x);
float cubed(float z);
char status(char ch);
void display(int x, int y, int z);
void printone(char c, int x, float q);
void swap(long x, long y);
bool thing(void);
double test_for_whatever(int, float, bool);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 273
Functions - No Arguments
Returns Nothing
#include <iostream>
using namespace std;
void put_asterisk(void);
Passed Nothing
int i;
int main()
{
put_asterisk();
put_asterisk();
put_asterisk(); Note
return(0);
}
void put_asterisk()
{
cout << “*”;
}
Note: void means no argument expected
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 274
Notes: 137
2006 C++ Course Handouts January 2006
void main()
{
char ch1='*';
char ch2='$';
char ch3='A';
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 275
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 276
Notes: 138
2006 C++ Course Handouts January 2006
float getRadius();
float square(float);
void main()
{
const float pi = 3.14159;
float rad;
float getRadius()
{
float radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
return radius;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 277
Pre-defined Functions
int x=25;
float y=3.2;
sqrt(x) returns 5
pow(2, 5) returns 32
abs(-9) returns 9
labs(-90000) returns 90000
fabs(-7.56) returns 7.56
ceil(y) returns 4.0 rounded up
ceil(3.9) returns 4.0 rounded up
floor(y) returns 3.0 rounded down
floor(3.9) returns 3.0 rounded down
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 278
Notes: 139
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 279
Answer = (double_it(triple(square(cube(myValue)))));
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 280
Notes: 140
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 281
Default Arguments
#include <iostream>
using namespace std;
void main()
{
displayStars(); // Uses default values cols and rows
cout << endl;
displayStars(5); // Uses 5 for cols and default value for rows
cout << endl;
displayStars(7, 3); // Uses 7 for cols and 3 for rows
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 282
Notes: 141
2006 C++ Course Handouts January 2006
Graphical Representation
Windows
or
Main()
DOS
Function A
Function D
Function B Function C
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 283
Variable Scope
// code verified 10/31/2002
#include <iostream>
int y = 60; // Global Variable
int displaytext(int abc); // prototype scope
void main(void)
{
int x = 10; // Local to the main
cout << "Displaytext Returns " << displaytext(x);
cout << endl;
}
Generated Output
x=90 y=60 abc=10
Displaytext Returns 90
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 284
Notes: 142
2006 C++ Course Handouts January 2006
Variable Scope
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 285
Global Variables
Variables defined outside of any function have global scope and
thus are available from any function in the program, including
main().
Local variables with the same name as global variables do not
change the global variables. A local variable with the same name
as a global variable hides the global variable, however. If a
function has a variable with the same name as a global variable,
the name refers to the local variable--not the global--when used
within the function.
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 286
Notes: 143
2006 C++ Course Handouts January 2006
Variable Scope
#include <iostream>
int cube_it(int x); // prototype scope
int cube_it(int c)
{
int cubed_value=0; // local to the function
cubed_value=c*c*c;
return(cubed_value);
Code Verified 10/31/2001
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 287
#include <iostream>
using namespace std; Code Verified 5/31/2001
int main(void)
{
double cube;
cube = cube_it(10.0);
cout << cube << endl << endl;
return(0);
}
double cube_it(double c)
{
double cubed_value=0.0;
cubed_value=c*c*c;
return(cubed_value);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 288
Notes: 144
2006 C++ Course Handouts January 2006
Return Values
return 5; // returns 5
return (5); // returns 5
return (x > 5); // returns true if x > 5
return (MyFunction()); // calls MyFunction
return; // simply bails out
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 289
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 290
Notes: 145
2006 C++ Course Handouts January 2006
void showVariable()
{
auto int myNum=0; // default
cout << "StatNum is " << myNum << endl;
myNum++;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 291
void showVariable()
{
int myNum=0;
cout << "StatNum is " << myNum << endl;
myNum++;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 292
Notes: 146
2006 C++ Course Handouts January 2006
void showVariable()
{
static int myNum=0;
cout << "StatNum is " << myNum << endl;
myNum++;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 293
Break
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 294
Notes: 147
2006 C++ Course Handouts January 2006
Call by Value
// code verified 10/31/2002
int a,b;
void swap(int x, int y);
Generated Output
a=100
b=200
a=100
b=200
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 295
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 296
Notes: 148
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 297
Swap Example
void get_input(int& n1, int& n2); // Prototype, formal parameters
void swap(int& n1, int& n2);
void main(void) Code verified 6/26/2001
{
int first_num, second_num;
get_input(first_num, second_num);
swap(first_num, second_num);
cout << "Number One Entered:" << first_num << endl;
cout << "Number Two Entered:" << second_num << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 298
Notes: 149
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 300
Notes: 150
2006 C++ Course Handouts January 2006
Function Overloading
Functions with the same name but with different argument
lists
Example: Say we want to square a number, but want to
pass it different types of variables. (long, int, float,
double, for instance)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 301
Function Overloading
// code verified 10/31/2002
#include <iostream>
using namespace std;
int cube(int);
float cube(float);
int int_input;
float flt_input;
void main(void)
{
cout << "Enter an integer to cube:";
cin >> int_input;
cout << "Enter a float to cube:";
cin >> flt_input;
cout << int_input << " cubed is " << cube(int_input) << endl;
cout << flt_input << " cubed is " << cube(flt_input) << endl;
}
int cube(int n) {
return(n*n*n);
}
float cube(float n) {
return(n*n*n);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 302
Notes: 151
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 303
Function Overloading
int square(int q) {
return(q*q);
}
double square(double q) {
return(q*q);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 304
Notes: 152
2006 C++ Course Handouts January 2006
Function Overloading
int mean(int n1, int n2, int n3);
int mean(int n1, int n2, int n3, int n4);
int main(void)
{
m = mean(2, 4, 6);
m = mean(100, 120, 233, 444);
return(0);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 305
Function Overloading
bool deposit(double amt, string acct);
bool deposit(string date, double amt, string acct);
int main(void)
{
deposit(date, amount, account);
deposit(amount, account);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 306
Notes: 153
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 307
cout << num0 << " Squared is " << square(num0) << endl;
cout << num1 << " Squared is " << square(num1) << endl;
cout << num2 << " Squared is " << square(num2) << endl;
cout << num3 << " Squared is " << square(num3) << endl;
cout << num4 << " Squared is " << square(num4) << endl;
cout << "10 Squared is " << square(10) << endl;
cout << "10.21 Squared is " << square(10.21) << endl;
cout << "10.21F Squared is " << square(10.21F) << endl;
cout << "Completed...\n\n";
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 308
Notes: 154
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 309
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 310
Notes: 155
2006 C++ Course Handouts January 2006
int main(void)
{
int x = 10;
cout << “Initial:” << x << endl;
cube_it(x);
int cube_it(int x)
return(0); {
} int value;
value= x * x * x;
cout << value;
return(value);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 311
Review Questions
1. What are the three main pieces you need to consider when
designing and using a function?
2. What type of arguments can be passed to a C++ function?
3. Is there a particular order to the arguments passed to a
function?
4. What is the scope of a global variable?
5. The ceil() function is known as what type of C++ function?
6. The “return” function, when used without an argument, is used
to __________?
7. Which “Call by” method can be used to modify a function’s
arguments?
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 312
Notes: 156
2006 C++ Course Handouts January 2006
Homework
1. Should have read Chapters 1 through 6 by now
2. Read Chapter 7 for next week
3. Work on your term paper
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 313
Chapter 6 Summary
C++ Functions
Built-in Functions
User Defined Functions
Definitions
Prototypes
Calling by Reference
Calling by Value
Overloading
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 314
Notes: 157
2006 C++ Course Handouts January 2006
Chapter 7
Data Structures and Classes
¾ Classes
¾ Encapsulation
¾ Constructors
¾ Struct Type
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 315
Data Structures
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 316
Notes: 158
2006 C++ Course Handouts January 2006
Data Structures
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 317
Data Structures
struct CDAccount // Structure Tag or Template
{
double balance; // Member Names
double interest_rate;
int term; Define the data type
};
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 318
Notes: 159
2006 C++ Course Handouts January 2006
Data Structures
int main(void)
{
Time now; // structure variable
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 319
Data Structures
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
struct Circle // Structure Tag or Template
{
double radius;
double diameter;
double area;
};
const double pi=3.14159;
void main(void)
{
Circle c; // structure variable
// Get user input
cout << "Enter the diameter:";
cin >> c.diameter;
// Do calculations
c.radius = c.diameter / 2;
c.area = pi * pow(c.radius, 2.0);
// Do Output
cout << fixed << showpoint << setprecision(2);
cout << "Radius: " << setw(6) << c.radius << endl;
cout << " Area: " << setw(6) << c.area << endl;
}
Code verified 04/14/03
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 320
Notes: 160
2006 C++ Course Handouts January 2006
DOT Operator
Syntax:
Structure_Variable_Name.Member_Variable_Name
Example:
struct StudentRecord
{
int student_number;
int student_age;
char student_grade;
};
int main(void)
{
StudentRecord your_record;
your_record.student_number = 20082;
your_record.student_grade = ‘A’; Code verified 11/04/01
your_record.student_age=32;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 321
Initializing a Structure
struct StudentRecord
{
int student_number;
int student_age;
char student_grade;
};
int main(void)
{
StudentRecord your_record={12345, 32, ‘A’};
// or
your_record.student_number=12345;
your_record.student_age=32;
your_record.student_grade=‘A’;
}
Code verified 11/04/01
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 322
Notes: 161
2006 C++ Course Handouts January 2006
Data Structures
#include <iostream>
using namespace std;
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;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 323
struct book
{ // Structure Template
char title[30];
char author[25];
int quantity;
float cost;
} library; // Structure Variable
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 324
Notes: 162
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 325
#include <iostream>
using namespace std;
struct book
{ // Structure Template
char title[30];
char author[25];
int quantity;
float cost;
} library; // Structure Variable
// Prototypes
float calculate(float, int);
void get_input(float&, int&);
int main(void)
{
get_input(library.cost, library.quantity);
cout << calculate(library.cost, library.quantity) << endl;
return(0);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 326
Notes: 163
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 327
Circle getInfo()
{ Validated 11/22/2003
Circle round;
cout << "Enter the diameter of a circle: ";
cin >> round.diameter;
round.radius = round.diameter / 2;
return round;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 328
Notes: 164
2006 C++ Course Handouts January 2006
Nested Structures
struct ChkDate
{ Validated 11/04/2001
int year;
int month;
int day;
}; // Structure Variable
struct book
{ // Structure Template
char title[30];
char author[25];
int quantity;
float cost;
ChkDate check_out;
}; // Structure Variable
book library;
ChkDate date;
int main(void)
{
ChkDate newdate = {2000, 02, 22}; // initializing
cout << library.check_out.day;
cout << date.year << endl;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 329
Nested Structures
struct AnnualCostInfo
{
float food, medical, license, misc;
}; Validated 11/22/2003
struct PetInfo
{
string name; Annual costs for my 5-year-old cat Sassy are $457.00
string type;
int age;
AnnualCostInfo cost;
};
void main()
{
PetInfo pet; // Define a structure variable
pet.name = "Sassy";
pet.type = "cat";
pet.age = 5;
pet.cost.food = 250.00;
pet.cost.medical = 150.00;
pet.cost.license = 7.00;
pet.cost.misc = 50.00;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 330
Notes: 165
2006 C++ Course Handouts January 2006
Structure Constructors
struct Employee
{
int employees; Validated 11/22/2003
int year;
float payrate;
Employee() Employees: 120
{ Fiscal Year: 2004
employees =120;
year =2004; Starting Rate: 25.55
payrate =25.55;
}
};
void main(void)
{
Employee emp;
cout << " Employees: “ << emp.employees << endl;
cout << " Fiscal Year: “ << emp.year << endl;
cout << "Starting Rate: “ << emp.payrate << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 331
Structure Constructors
#include <iostream.h>
struct Employee
{ Validated 11/22/2003
int employees;
int year;
float payrate;
void main(void)
{
Employee emp(120, 2004, 25.55);
cout << " Employees: “ << emp.employees << endl;
cout << " Fiscal Year: “ << emp.year << endl;
cout << "Starting Rate: “ << emp.payrate << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 332
Notes: 166
2006 C++ Course Handouts January 2006
struct {
unsigned field1 : 1; // max value is 1
unsigned field2 : 1;
unsigned field3 : 3; // max value is 7
unsigned field4 : 3;
} mybits;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 333
struct {
unsigned first : 1;
: 2;
unsigned second : 1;
: 3;
unsigned third : 2;
} gaps;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 334
Notes: 167
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 335
Unions (1 of 2)
1 of 2
Validated 11/22/2003
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 336
Notes: 168
2006 C++ Course Handouts January 2006
Unions (2 of 2)
void main()
{
PaySource employee1; // employee1 is a PaySource union.
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 337
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 338
Notes: 169
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 339
Classes
Classes hold member functions as well as variables
Syntax
class class_name
{
public:
member specification-1
member specification-2
member specification-3
member specification-n
private:
member specification-n+1
member specification-n+2
member specification-n+3
member specification-n+4
};
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 340
Notes: 170
2006 C++ Course Handouts January 2006
Classes
Classes hold member functions as well as variables
class class_name
{
public:
member specification-1
Once a class is defined, an
member specification-2 object is created. An object
member specification-3
member specification-n is similar to a variable of
private:
member specification-n+1
the class type
member specification-n+2
member specification-n+3
member specification-n+4
};
int main(void)
{
class_name object_name;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 341
Classes
Classes hold member functions as well as variables
#include <iostream>
using namespace std; Code verified 11/04/2001
class DayOfYear
{
public: // Public members
void output(); // member function prototype
int month;
int day;
int year;
private:
float cost;
};
DayOfYear today, birthday; // Declare abstract variables
int main(void)
{ Scope Resolution Operator
cin >> today.month;
cin >> today.day;
cin >> today.year;
today.output();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 342
Notes: 171
2006 C++ Course Handouts January 2006
Classes
#include <iostream>
using namespace std;
class DayOfYear
{
public: // Public members Code verified 11/06/2001
void output(); // member function prototype
int month; // variables
int day;
int year;
private:
float cost; // Can only be used in member functions
};
DayOfYear today, birthday; // Declare abstract variables
void main(void)
{
cin >> today.month;
cin >> today.day;
cin >> today.year;
// cin >> cost; // Error since cost is private
cin >> birthday.month;
cin >> birthday.day;
cin >> birthday.year; Classes hold member
today.output();
birthday.output(); functions as well as
} variables
void DayOfYear::output() // Member Function
{
cout << month << "/" << day << "/" << year << endl;
cout << cost << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 343
Classes
class DayOfYear
{
Private Members
public:
void output(); // member function prototype
void get_dates(); // member function prototype
int month;
int day; Code verified 11/06/2001
int year;
private:
int birth_year;
};
DayOfYear today, birthday; // Declare abstract variables
void main(void)
{
today.get_dates(); // Load today
today.output(); // Dump today
birthday.get_dates(); // Load birthday
birthday.output(); // Dump birthday
}
Notes: 172
2006 C++ Course Handouts January 2006
Constructors
Used to initialize classes
Must be in the public section of the class
Cannot return a value (Must be void)
Must have same name as class
class BankAccount
{
public:
BankAccount(int dollars, int cents, double rate);
BankAccount(int dollars, double rate);
BankAccount(); // default constructor
voidoutput(ostream&, outs);
private:
double balance;
double interest_rate;
};
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 345
Constructors
int main(void)
{
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 346
Notes: 173
2006 C++ Course Handouts January 2006
Constructors
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 347
class mathClass
{
public:
mathClass();
void add();
void subtract();
void multiply ();
void divide();
void getInput();
private:
double num1,num2,result;
};
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 348
Notes: 174
2006 C++ Course Handouts January 2006
void mathClass::getInput()
{
cout << "Jim's Math Machine.......\n\n";
cout << " Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
}
void mathClass::add()
{
result=num1+num2;
cout<<"The sum of the numbers is: "<<result<< endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 349
void mathClass::subtract()
{
result=num1-num2;
cout<<"The Difference between the numbers is: "<<result<< endl;
}
void mathClass::divide()
{
result=num1/num2;
cout<<"The quotient of the numbers is: "<<result<< endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 350
Notes: 175
2006 C++ Course Handouts January 2006
void main()
{
mathClass math;
math.getInput();
math.add();
math.subtract();
math.multiply();
math.divide();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 351
Review Questions
#include <iostream>
using namespace std;
structure book {
char title[30]; Find the error in the
char author[25];
int
float
quantity;
cost;
following structure
};
void main(void)
{
book library; // Structure Variable
cout << " Enter Book Title:";
cin >> library.title;
cout << "Enter Authors Name:";
cin >> library.author;
cout << " Enter Recent Cost:";
cin >> library.cost;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 352
Notes: 176
2006 C++ Course Handouts January 2006
Review Questions
#include <iostream>
using namespace std;
Find the error in the
class DayOfYear
{
public:
following class
void output(); // member function prototype
void get_dates(); // member function prototype
int month;
int day;
int year;
private:
int birth_year;
};
DayOfYear today, birthday; // Declare abstract variables
void main(void)
{
today.get_dates(); // Load today
today.output(); // Dump today
birthday.get_dates(); // Load birthday
birthday.output(); // Dump birthday
cin >> today.birth_year;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 353
Homework
1. Should have read Chapters 1 through 7 by now
2. Read Chapter 8 for next week
3. Work on your term paper
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 354
Notes: 177
2006 C++ Course Handouts January 2006
Chapter 7 Summary
Classes
Constructors
Structures
Initializing
Structures
Passing Structures as
Arguments
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 355
Chapter 8
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 356
Notes: 178
2006 C++ Course Handouts January 2006
Arrays
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 357
Arrays
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 358
Notes: 179
2006 C++ Course Handouts January 2006
Arrays
Declaring an Array
#define SIZE 100
char name[25];
int counts[1000];
double prices[90];
int quan[SIZE];
int table[5][5];
char matrix[10][20];
unsigned short int mat[6][5];
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 359
Arrays
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 360
Notes: 180
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 361
Common Error
Declaring an Array
int score[5];
index = 12;
score[index];
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 362
Notes: 181
2006 C++ Course Handouts January 2006
Common Error
int counts[5] = {2,4,6,8,10};
int i = 1000;
Before 2 4 6 8 10 1000 0
After 0 0 0 0 0 0 0
Trouble Here
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 363
Arrays
January has 31 days.
February has 28 days.
March has 31 days.
April has 30 days.
May has 31 days.
#include <iostream>
June has 30 days.
#include <iomanip>
July has 31 days.
#include <string>
August has 31 days.
#define MONTHS 12
September has 30 days.
October has 31 days.
using namespace std;
November has 30 days.
December has 31 days.
void main()
{
string month[]={"January", "February", "March", "April", "May",
"June", "July", "August“, September", "October", "November", "December"};
int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
int i;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 364
Notes: 182
2006 C++ Course Handouts January 2006
Arrays
#include <iostream>
#include <iomanip>
#include <string>
#define MONTHS 12 Enter the Month to Print(1-12): 2
You requested February
using namespace std;
void main()
{
string month[]= {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"};
int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
int month_input;
month_input--;
cout << "You requested " << month[month_input] << endl << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 365
Arrays
100 101 102 103 104 105 106 107 108 109
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 366
Notes: 183
2006 C++ Course Handouts January 2006
Array Initialization
Code verified 11/17/2001
#include <iostream>
using namespace std;
void main()
{
int children[3] = {2, 12, 3};
char codes[4] = {'A', 'C', 'Z', '$'};
long vectors[] = {12, 23, 43, 54, 2, 99, 21};
int n;
int size;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 367
Initializing Arrays
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 368
Notes: 184
2006 C++ Course Handouts January 2006
Initializing Arrays
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 369
Common Error
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 370
Notes: 185
2006 C++ Course Handouts January 2006
Coding Practice
#include <iostream>
const int MAX_PEOPLE = 20;
main(void)
{
int array_employee_numbers[MAX_PEOPLE];
int n=0;
for (n=0; n<MAX_PEOPLE; n++)
array_employee_numbers[n]=0;
}
Code verified 11/17/2001
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 371
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 372
Notes: 186
2006 C++ Course Handouts January 2006
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];
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 373
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 374
Notes: 187
2006 C++ Course Handouts January 2006
Multidimensional Arrays
char page[30][100];
This array has two indexes
The first is from 0 to 29
the second is from 0 to 99
page[0][0], page[0][1] … page[0][99]
page[1][0], page[1][1] … page[1][99]
page[2][0], page[2][1] … page[2][99]
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 375
Arrays of Strings
char names[45][100];
char addresses[45][100];
Smith
Leonard
Wilson
Dotolo
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 376
Notes: 188
2006 C++ Course Handouts January 2006
Dynamic Arrays
#include <iostream>
using namespace std;
void main(void)
{
int array_size=0;
int i=0;
delete [] arr;
} Code verified 11/17/2001
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 377
Review Questions
1. Arrays in C++ start at the __________ element?
2. Arrays of characters are sometimes called _____?
3. What is a common error when using arrays?
4. Find the errors in the following array declarations.
1. int array1(1000);
2. char name{45};
3. float costs[ ] = 12.99, 23.45, 45.12;
5. Find the errors in the following array statements.
1. array1[1001]=100;
2. name[-1]=‘a’;
3. costs(1)=12.98;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 378
Notes: 189
2006 C++ Course Handouts January 2006
Homework
1. Should have read Chapters 1 through 8 by now
2. Read Chapter 9 for next week
3. Work on your term paper
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 379
Chapter 8 Summary
Arrays Summary
Single Dimension
Multi Dimension
Static and Dynamic
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 380
Notes: 190
2006 C++ Course Handouts January 2006
Exchange Sort
Selection Sort
Merge Sort
Quick Sort
Binary Search
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 381
Sorting an Array
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 382
Notes: 191
2006 C++ Course Handouts January 2006
#include <time.h>
clock_t tv1, tv2;
double time;
tv1 = clock();
tv2 = clock();
time = (tv2 - tv1)/(CLOCKS_PER_SEC / (double) 1000.0);
Notes: 192
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 385
Bubble Sort (1 of 3)
#include <iostream>
#include <time.h>
using namespace std;
void initialize_array(void);
int sort_it(int a[]);
void main()
Know as the n-squared method
{
Also known as the exchange sort.
int swaps;
clock_t tv1, tv2;
double time;
initialize_array();
tv1 = clock();
swaps=sort_it(main_array);
tv2 = clock();
time = (tv2 - tv1)/(CLOCKS_PER_SEC / (double) 1000.0);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 386
Notes: 193
2006 C++ Course Handouts January 2006
Bubble Sort (2 of 3)
// sort the array
int sort_it(int arr[])
{
int x, swap;
int swaps=0;
bool we_swapped_one=false;
// do the sort
do
{
we_swapped_one=false;
for (x=0; x<SIZE-1; x++)
{
if (arr[x]>arr[x+1])
{
swap=arr[x];
arr[x]=arr[x+1];
arr[x+1]=swap;
swaps++;
we_swapped_one=true;
}
} // end of inner for loop Know as the n-squared method
}
while (we_swapped_one); Also known as the exchange sort.
return(swaps);
} // end of function sort_it
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 387
Bubble Sort (3 of 3)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 388
Notes: 194
2006 C++ Course Handouts January 2006
Shaker Sort
Shaker Sort Algorithm Discussion
1. A Shaker Sort is bi-directional bubble sort
because we work from both ends
2. Alternate movements between 0 and n on one
pass to n and 0 on the next pass. This will move
an element right to the top or bottom depending
on which way you are moving.
3. It gets its name because of the way it moves
about the list, back and forth like a salt shaker or
the popular beverage mixer.
4. http://users.net1plus.com/brianl/ShakerSort.htm
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 389
Selection Sort
0 1 2 3 4
Selection Sort Algorithm
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 390
Notes: 195
2006 C++ Course Handouts January 2006
Selection Sort
Algorithm
1. Find the smallest element in the
set 0-n
2. Exchange with the zero element
3. Find the smallest in 1-n
4. Exchange with the 1st element
5. Find the smallest in 2-n
6. Exchange with the 2nd element
7. Find the smallest in 3-n
8. Exchange with the 3rd element
9. Continue until the n-th element
is reached
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 391
Selection Sort
Selection Sort Discussion
Methods
1. Search for the lowest element starting from nth element
2. Swap the lowest element with nth element
180
150
120
90
60
30
10 20 30 40 50 60 70 80 90 100
N (thousands)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 392
Notes: 196
2006 C++ Course Handouts January 2006
void initialize_array(void);
int sort_it(int a[]);
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);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 393
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 394
Notes: 197
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 395
http://www.ship.edu/~cawell/Sorting/selintro.htm
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 396
Notes: 198
2006 C++ Course Handouts January 2006
Searching an Array
Picture a phonebook
How would you find a number by
name?
¾ Search alphabetically
How would you find a name by using a
number?
¾ Search linearly
Linear Search
¾ Start at the beginning and test every
occurrence
Binary Search
¾ Sort the data
¾ Successive slicing in half
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 397
Sequential Search
#include <string.h>
#include <iostream>
using namespace std;
int k, size;
int a[]={32,43,54,65,90,21,23,34,45,65, 67,879, 89, 200,
33, 41, 34};
Output
int main(void)
{ Hit:32
size = sizeof(a) / sizeof(int);
Hit:43
for (k=0; k<size; k++)
{ Hit:21
if (a[k] < 50)
cout << "Hit:" << a[k] << endl; Hit:23
}
return(0); Hit:34
}
Hit:45
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 398
Notes: 199
2006 C++ Course Handouts January 2006
Binary Search
Say we have 100 million phone numbers
Sort the numbers
If we are looking for 555-480-9400
To see how many tests we need we need
to use logarithms
Searches = log2x, where x is the total number of items
Searches = log2100000000 for example
How to solve:
Searches = Log10100000000 / Log102
Searches = 8 / 0.301029996
Searches = 26.57 or rounded up to 27
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 399
Binary Search
First, Sort the data
Then, by successively cutting the array of data in half, you can narrow
down the search
1. Say we are looking for 303
2. See how any elements are in the array
3. Choose the middle position (5 in this case)
4. Compare the value at 5 (333) against the search argument (303)
Num(0) 204
Num(1) 222
Num(2) 303
Num(3) 321
Num(4) 324
Num(5) 333 Middle Position
Num(6) 356
Num(7) 411
Num(8) 444
Num(9) 504
Num(10) 621
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 400
Notes: 200
2006 C++ Course Handouts January 2006
void main()
{
int results, empID=1, swaps;
initialize_array();
swaps=sort_it(main_array);
cout << "Swaps:" << swaps << endl;
while( empID != 0)
{
cout << "Enter the employee ID you wish to search for: ";
cin >> empID;
results = binarySearch(main_array, SIZE, empID);
if (results == -1)
cout << "That number does not exist in the array.\n";
else
{
cout << "That ID is found at element " << results;
cout << " in the array.\n";
}
} // end of while loop
} // end of main
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 401
return position;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 402
Notes: 201
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 403
// do the sort
do
{
we_swapped_one=false;
for (x=0; x<SIZE-1; x++)
{
if (arr[x]>arr[x+1])
{
swap=arr[x];
arr[x]=arr[x+1];
arr[x+1]=swap;
swaps++;
we_swapped_one=true;
}
} // end of inner for loop
}
while (we_swapped_one);
return(swaps);
} // end of function sort_it
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 404
Notes: 202
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 405
Chapter 9 Summary
Bubble Sorts
Selection Sorts
Binary Search
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 406
Notes: 203
2006 C++ Course Handouts January 2006
Strings
Character Arrays
String Functions
String Class
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 407
String Basics
Null Character, \0
Also known as low-values
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 408
Notes: 204
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 409
String Data
Strings in C++ are no more
than an array of characters.
#include <iostream>
using namespace std;
char name[40]; // 40 characters
char address[50]; // 50 characters
char state[3];
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 410
Notes: 205
2006 C++ Course Handouts January 2006
cout << "The string " << sentence << " has " << count
<< " characters and is stored in " << count+1 << " bytes\n";
}
0 is same as null is same as ‘\0’
Output:
The string Hello World has 11 characters and is stored in 12 bytes
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 411
Strings in C++
char name[20] = “SMITH “;
Example:
name[5]=‘\0’; // optionally name[5]=0;
cout << name << endl’
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 412
Notes: 206
2006 C++ Course Handouts January 2006
Strings in C++
C I S 1 6 2 \0
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 413
0 48 00110000
1 49 00110001
2 50 00110010
3 51 00110011
4 52 00110100
5 53 00110101
6 54 00110110
7 55 00110111
8 56 00111000
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 414
Notes: 207
2006 C++ Course Handouts January 2006
ASCII v. Numeric 32
! 33
" 34
# 35
#include <iostream> $ 36
using namespace std; % 37
& 38
' 39
void main() ( 40
{ ) 41
int counter; * 42
+ 43
, 44
for (counter=32; counter<255; counter++) - 45
{ . 46
cout.width(1); / 47
0 48
cout << (char) counter; 1 49
cout.width(4); 2 50
cout << counter << endl; 3 51
4 52
}
5 53
} 6 54
7 55
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 415
ASCII v. Numeric
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 416
Notes: 208
2006 C++ Course Handouts January 2006
String or Character
char ch;
ch = ‘A’; // character A stored in memory
ch = “A”; // character A followed by \0
ch = A; // loads ch with the variable A
ASCII
American Standard Code for Information Interchange
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 417
String Literals
A set of characters
“string literal” wrapped on double quotes
¾ Characters wrapped in single quotes
¾ Strings wrapped in double quotes
Also called a character array
Max length ANSI, is 509 bytes
Max length, Microsoft, is 2008 bytes
Always end with NULL (Binary Zero, \0)
cout << “This is a string literal..”;
char msg1[]=“This is a C string literal”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 418
Notes: 209
2006 C++ Course Handouts January 2006
Or
C++ Prototype
char strcpy(char *str1, char *str2)
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 419
strncpy()
prototype
strncpy(strcpy(char *str1, char *str2, int count)
Examples
strncpy(str1, str2, count)
strncpy(str1, str2, count+1)
strncpy(str1, str2, 12)
Note:
if str1 cannot hold the contents of str2 then
behavior is undefined.
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 420
Notes: 210
2006 C++ Course Handouts January 2006
strcpy(address_3, address_1);
strcat(address_3, address_2);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 421
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 422
Notes: 211
2006 C++ Course Handouts January 2006
// Method Two
if (strcmp(message, "This is a string") == 0)
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";
// Method Three
if (! strcmp(message, "This is a string"))
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 423
// Method 2
if (strncmp(message, "This is a", 9) == 0)
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";
// Method 3
if (! strncmp(message, "This", 4))
cout << "Strings are the same\n";
else
cout << "Strings are NOT the same\n";
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 424
Notes: 212
2006 C++ Course Handouts January 2006
Common Error
Proper method:
strcpy(message, “This is a string”);
strcpy(message, myString);
Assume:
char message[40]=“Test String One”;
char myString[40]=“My String Data”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 425
Common Error
This is Illegal:
if (message == “This is a string”)
do_something; < 0: str1 is less than str2
= 0: str1 = str2
> 0: str1 is greater than str2
Proper method:
if (strcmp(message, “This is a string”))
cout << “Strings are NOT the same”;
else
cout << “Strings are the same”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 426
Notes: 213
2006 C++ Course Handouts January 2006
strlen() function
Remember:
sizeof() shows the length of the variable space
strlen() shows the actual length of the string contents
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 427
Application
One use for strlen()
To test for an empty input string. Examples:
int x;
cin >> name;
x = strlen(name);
if (x == 0)
{
cout << “Invalid Named Entered \n”;
}
or
if (strlen(name) == 0)
{
cout << “Invalid Named Entered \n”;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 428
Notes: 214
2006 C++ Course Handouts January 2006
getchar()
reads a character from the keyboard
#define LF 10
int count;
char name[30];
int main(void)
{
count=0;
while (count < 30)
{
name[count] = getchar();
if (name[count] == LF)
{
name[count]=0;
break;
}
count++;
}
cout << name << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 429
putchar()
writes a character to the screen (stream I/O)
#include <iostream.h> // for cout
#include <stdio.h> // for putchar
#include <string.h> // for strlen
int x, length;
char name[30]="Samira Munoz\0";
void main(void)
{ Code verified 11/17/2001
x=0;
length=strlen(name);
// Write the name once
while (x < length)
{
putchar(name[x]);
x++;
}
// Write the name again
cout << endl << name << endl;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 430
Notes: 215
2006 C++ Course Handouts January 2006
char ch;
void main(void)
{
while ((ch = getchar()) != EOF)
putchar(ch);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 431
puts(stringvar);
puts(“Literal”);
gets(stringvar);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 432
Notes: 216
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 433
Examples:
char st[30];
cin.getline(st, 30);
cin.getline(st, sizeof(st));
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 434
Notes: 217
2006 C++ Course Handouts January 2006
ch = ‘a’;
cout << toupper(ch); // Prints 65
ch = ‘a’;
cout << tolower(ch); // Prints 97
Why ?
toupper and tolower return integer results
Be Careful when embedding
these functions in the cout object
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 435
ch = ‘a’;
cout << (char) toupper(ch); // Prints A
ch = ‘A’;
cout << (char) tolower(ch); // Prints a
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 436
Notes: 218
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 437
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 438
Notes: 219
2006 C++ Course Handouts January 2006
char ch;
ch = getchar();
if (ispunct(ch))
cout << “Punctuation Character Found”;
char ch;
ch = getchar();
if (isspace(ch))
cout << “We have a Space Character”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 439
char ch;
ch = getchar();
if (isxdigit(ch))
cout << “Hex Digit Encountered”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 440
Notes: 220
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 441
Length of String: 7
Length of x: 4
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 442
Notes: 221
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 443
strupr()
strupr(name);
cout << name << endl;
prints
CHARLES BABBAGE
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 444
Notes: 222
2006 C++ Course Handouts January 2006
strlwr()
strlwr(name);
cout << name << endl;
prints
charles babbage
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 445
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 446
Notes: 223
2006 C++ Course Handouts January 2006
strstr()
char strstr(char *str1, char *str2)
Returns a pointer to the first occurrence in str1 of the string pointed to by
str2.
char *p;
p = strstr(“This is a test”, ”te”);
if (p == 0)
cout << “No Find”;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 447
strspn Function
/* STRSPN.C: This program uses strspn to determine
* the length of the segment in the string "cabbage"
* consisting of a's, b's, and c's. In other words,
* it finds the first non-abc letter. */
#include <string.h>
#include <stdio.h>
Generated Output
The portion of 'cabbage' containing only a, b, or c is 5 bytes
long
Courtesy MSDN Online
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 448
Notes: 224
2006 C++ Course Handouts January 2006
char array[1000];
memset(array, ‘ ‘, 1000);
char array[1000];
char buffer[1000]; Not in Book
memcpy(array, buffer, 1000);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 449
String Class
#include <string>
Code Verified
#include <iostream>
10/29/2002
using namespace std;
void main(void)
{
string first_name, last_name;
first_name="Abraham";
last_name="Lincoln";
cout << first_name << " " << last_name << endl;
cout << first_name.capacity();
cout << "\n\n\n";
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 450
Notes: 225
2006 C++ Course Handouts January 2006
String Class
Member Functions
At
Append
Assign
Begin
Copy
Capacity
Compare
End
Erase
Find
Insert
Length
Replace
Size
Swap
Substr
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 451
String Class
#include <string>
#include <iostream>
using namespace std;
int main(void) Generated Output
{
string first_name, last_name; Allen 5 31
string whole_name;
Shepard, Allen
first_name="Allen";
last_name="Shepard"; Shepard Allen
whole_name=last_name;
whole_name.append(", "); Shepard
whole_name.append(first_name);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 452
Notes: 226
2006 C++ Course Handouts January 2006
String Class
#include <string>
#include <iostream>
using namespace std; Generated Output
void main(void) Shpard, Al
{
string first_name, last_name; 3
string whole_name;
long ptr;
ShpQrd, Al
first_name="Allen";
last_name="Shepard";
whole_name=last_name;
whole_name.append(", ");
// append starting at 0, for 2 bytes
whole_name.append(first_name,0,2);
// erase 1 char starting pos 2, compress the str
whole_name.erase(2,1);
cout << whole_name << endl;
ptr = whole_name.find("ar");
cout << ptr << endl;
if (ptr > whole_name.capacity())
cout << "Cannot find selected substring\n\n";
else
{
whole_name.at(ptr) = 'Q';
cout << whole_name << endl;
}
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 453
Review Questions
1. Strings in C++ are simply ___________ arrays
2. A binary zero is 000000002 or 001100002
3. String Literals are wrapped with ______ quotes
4. The strlen() function can be used to __________
5. strcat() does what?
6. strcpy does what?
7. Explain isupper()
8. Explain tolower()
9. Explain atoi()
10. What String Class Member Function can be used to concatenate
two strings
11. What String Class Member Function can be used to replace a
specific character in a string
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 454
Notes: 227
2006 C++ Course Handouts January 2006
Homework
1. Should have read Chapters 1 through 10 and 12 by now
2. Work on your term paper
3. Work on Packet-3…
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 455
Chapter 12 Summary
String Class
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 456
Notes: 228
2006 C++ Course Handouts January 2006
Chapter 13
Stream I/O
Character I/O
Inheritance
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 457
C++
Program Disk File
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 458
Notes: 229
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 459
void main(void)
{
ofstream outstream; // output file object
outstream.open("c:/myfile.dat");
outstream << "Albert Einstein\n"; Albert Einstein
outstream << "Michael Faraday\n"; Michael Faraday
outstream << "Alexander Graham Bell\n"; Alexander Graham Bell
Jimi Hendrix
outstream << "Jimi Hendrix\n"; Kurt Cobain
outstream << "Kurt Cobain\n";
outstream.close();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 460
Notes: 230
2006 C++ Course Handouts January 2006
void main(void)
{
ifstream instream; // output file object
string celebrity;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 461
instream.open(“c:/myfile.dat”,ios::in|ios::nocreate);
instream.close();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 462
Notes: 231
2006 C++ Course Handouts January 2006
int main()
{
fstream dataFile;
string buffer;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 463
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 464
Notes: 232
2006 C++ Course Handouts January 2006
#include <iostream>
#include <fstream.h>
using namespace std;
void main()
{
char c;
ifstream infile(“myfile.dat");
ofstream outfile("yourFile.dat");
if (outfile && infile) // They will be 0 on err.
while (infile >> c)
outfile << c;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 465
char filestring[25]=“C:/MYFILE.DAT”;
char filename[45]=“D:/INV/MASTER.DAT”;
ifstream file_in, filex, payroll_master;
ofstream file_out, newfile, inventory_detail;
payroll_master.open(filestring, ios::in|ios::nocreate);
inventory_detail.open(filename, ios::app);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 466
Notes: 233
2006 C++ Course Handouts January 2006
Mode Flags
The open Function for Output Streams
To use an output file stream (ofstream), you must associate that stream with a
specific disk file in the constructor or the open function. If you use the open
function, you can reuse the same stream object with a series of files. In either
case, the arguments describing the file are the same.
When you open the file associated with an output stream, you generally specify
an open_mode flag. You can combine these flags, which are defined as
enumerators in the ios class, with the bitwise OR ( | ) operator.
Flag Function
ios::app Opens an output file for appending.
ios::ate Opens an existing file (either input or output) and seeks the end.
ios::in Opens an input file. Use ios::in as an open_mode for an ofstream file to
prevent truncating an existing file.
ios::out Opens an output file. When you use ios::out for an ofstream object
without ios::app, ios::ate, or ios::in, ios::trunc is implied.
ios::nocreate Opens a file only if it already exists; otherwise the operation fails.
ios::noreplace Opens a file only if it does not exist; otherwise the operation
fails.
ios::trunc Opens a file and deletes the old file (if it already exists).
ios::binary Opens a file in binary mode (default is text mode).
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 467
void main()
{
fstream dataFile;
dataFile.open("demofile.txt", ios::out);
dataFile << "Jones\n";
dataFile << "Smith\n";
dataFile.close();
dataFile.open("demofile.txt", ios::out|ios::app);
dataFile << "Willis\n";
dataFile << "Davis\n";
dataFile.close();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 468
Notes: 234
2006 C++ Course Handouts January 2006
Dot Operator
Objects
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 469
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 470
Notes: 235
2006 C++ Course Handouts January 2006
fail() Example
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>
void main(void)
{
int i;
string data;
int count=0;
ifstream payroll_file;
payroll_file.clear();
payroll_file.open("C:/data/cpp/cis162/spring2003/numbers.txt", ios::in);
if (payroll_file.fail() != 0)
{
cout << "File Open Failed with Error Code: ";
cout << payroll_file.fail() << "\n";
cout << "Program Aborting...\n\n";
exit(1);
} Code Verified 11/23/02
for (i=0; i<10000; i++)
{
payroll_file >> data;
if (payroll_file.fail() != 0)
break;
count++;
}
cout << count << " Records processed...\n\n";
payroll_file.close();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 471
void main(void)
{
ifstream numbers_in;
ofstream numbers_out;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 472
Notes: 236
2006 C++ Course Handouts January 2006
eof() Example
#include <stdlib.h>
#include <iomanip> Code Verified 11/23/2002
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
string data;
long num;
void main(void)
{
ifstream payroll_file;
payroll_file.open("c:/data/cpp/cis162/spring2003/numbers.txt", ios::in);
if (payroll_file.fail() != 0)
{
cout << "File Open Failed with Error Code: ";
cout << payroll_file.fail() << "\n";
cout << "Program Aborting...\n\n";
}
else
{
while (! payroll_file.eof())
{
data="";
payroll_file >> data;
cout << setw(9) << data << endl;
}
payroll_file.close();
}
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 473
Open Modes
ifstream( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot );
The file protection specification; defaults to the static integer filebuf::openprot that is
equivalent to filebuf::sh_compat. The possible nProt values are:
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 474
Notes: 237
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 475
Character I/O
#include <fstream.h>
cin.get(char variable);
cout.put(char variable);
out_stream.put(char variable);
in_stream.get(char variable);
cin belongs to istream, NOT ifstream
cout belongs to ostream, NOT ofstream
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 476
Notes: 238
2006 C++ Course Handouts January 2006
fin.open("c:/data/c_programs/cis162ab/cross_ref.c");
fout.open("c:/data/c_programs/cis162ab/new.c");
if (fin.fail() != 0)
{
cout << "File Open Failed with Error Code: ";
cout << fin.fail() << "\n";
cout << "Program Aborting...\n\n";
exit(1);
}
while (!fin.eof())
{
fin.get(ch);
fout.put(ch);
cout.put(ch);
} Code Verified 5/30/01
fin.close();
fout.close();
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 477
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 478
Notes: 239
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 479
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 480
Notes: 240
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 481
Formatting Output
fileout.setf(ios::fixed);
fileout.setf(ios::showpoint);
fileout.precision(4);
setf attributes
ios::fixed // don’t use scientific notation
ios::scientific // use scientific notation
ios::showpoint // always show a decimal point
ios::showpos // show a plus on positive
ios::right // right justify
ios::left // left justify
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 482
Notes: 241
2006 C++ Course Handouts January 2006
I/O Manipulators
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 483
Write Method
Using write()
Syntax: oblect.write(variable, length);
#include <iostream>
#include <string>
using namespace std;
Output
void main ()
{
One if by land
char One[] = "One if by land"; One if
One
int fullLength = strlen(One);
int length2 = strlen(One)/2;
int length3 = strlen(One)/4;
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 484
Notes: 242
2006 C++ Course Handouts January 2006
file.seekg(5L, ios::beg);
file.get(ch);
cout << "Byte 5 from beginning: " << ch << endl;
file.seekg(-10L, ios::end);
file.get(ch);
cout << "Byte 10 from end: " << ch << endl;
file.seekg(3L, ios::cur);
file.get(ch);
cout << "Byte 3 from current: " << ch << endl;
file.close();
return 0;
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 485
// Function Prototypes
long byteNum(int);
void showRec(Info);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 486
Notes: 243
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 487
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 488
Notes: 244
2006 C++ Course Handouts January 2006
Examples:
sprintf(title,”%15s %8s %4i\n”, header, date, page);
sprintf(line,”%8s %8s %4i %c”, acct, date, quan, status);
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 489
%c character
%d signed decimal integer
%e,E floating point e-notation or E-notation
%f floating point decimal notation
%g,G use %f(F) or %e(E) whichever is shorter
%i signed decimal integer
%o unsigned octal integer
%p pointer
%s string
%u unsigned decimal integer
%x,X unsigned hex integer
%% percent sign
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 490
Notes: 245
2006 C++ Course Handouts January 2006
Format: %xy
where x is a modifier or flag
and y is the specification
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 491
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 492
Notes: 246
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 493
Review Questions
Name the two types of file I/O in C++?
The open statement is considered to be a _____ function.
ifstream is considered to be a _____________
We use ifstream and ofstream to instantiate a file _______?
What member function is used to determine if the previous I/O was
successful?
What member function is used to capture and report the end of a
file condition?
What must a programmer do to re-read the first line of a file?
What include directive do you need to process data files?
What happens to a data file when we open it for output?
Why would we want to close a file that was opened for input?
Why would we want to close a file that was opened for output?
What is a good use for the sprintf function?
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 494
Notes: 247
2006 C++ Course Handouts January 2006
Homework
1. Should have read Chapters 1 through 10 , 12 13 by now
2. Work on your term paper
3. Work on Homework Packets
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 495
Chapter 13 Summary
Stream I/O
Character I/O
fail()
good()
eof()
sprintf()
Manipulators
setf()
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 496
Notes: 248
2006 C++ Course Handouts January 2006
Advanced Topics
Bitwise Operators
Bit Fields
C-Style File I/O Operations
Recursion
Pointers
I/O Redirection
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 497
Interesting Facts
Most Computers, Intel, Motorola or anything else
use binary as the internal representation
Notes: 249
2006 C++ Course Handouts January 2006
Boolean Operations
AND Operation
OR Operation
XOR Operation
One’s Complement Operation
Left Shift
Right Shift
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 499
Bitwise Operations
Key to success
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 500
Notes: 250
2006 C++ Course Handouts January 2006
00101011 43
10101010 170
00101010 42 Remember to multiply
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 501
unsigned val=109;
unsigned mask=223; // Bitwise AND Operation
unsigned newval;
main()
{
109 223 77 m M
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 502
Notes: 251
2006 C++ Course Handouts January 2006
Bitwise OR Operation
00101011 43
10101010 170
10101011 171 Remember we’re adding, now
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 503
Bitwise OR Operation
#include <iostream.h>
#include <iomanip.h>
unsigned val=43;
unsigned mask=170; // Bitwise OR Operation
unsigned newval;
main()
{
Prints:
43 170 171
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 504
Notes: 252
2006 C++ Course Handouts January 2006
00101011 43
10101010 170
10000001 129 Remember we’re adding, Again
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 505
unsigned val=43;
unsigned mask=170; // Bitwise XOR Operation
unsigned newval;
main()
{
newval = val ^ mask;
cout << setw(4) << val << setw(4) << mask << setw(4) << newval;
return(0);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 506
Notes: 253
2006 C++ Course Handouts January 2006
Complement Operation
11111111 255
00000000 0
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 507
Shifting Operations
01011100 92
00101110 46
00010111 23
00001011 11
00000101 5
00000010 2
00000001 1
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 508
Notes: 254
2006 C++ Course Handouts January 2006
Shifting Operations
01011100 92
10111000 184
01110000 112
11100000 224
11000000 192
10000000 128
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 509
Shifting Example
#include <iostream.h>
#include <iomanip.h>
unsigned val=92;
int i;
main()
Prints:
{
92
for (i=0; i<9; i++)
{ 184
cout << setw(8) << val << endl; 368
val = val << 1; 736
} 1472
return(0); 2944
} 5888
11776
23552
Prints:
92 184 368 736 46 23
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 510
Notes: 255
2006 C++ Course Handouts January 2006
C++ Pointers
#include <iostream>
#include <iomanip>
using namespace std;
int x;
void main(void)
{
x=6000;
cout << setw(8) << x << setw(18) << &x << endl;
}
Output:
Verified 11/27/2003
6000 00477748
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 511
C++ Pointers
#include <iostream>
using namespace std; Address of x: 00477738
double d1;
Address of iptr: 0047773C
double d2; Contents of iptr: 00477738
int x; Value of x: 100
int *iptr; Contents of dptr1: 00477750
double *dptr1; Contents of dptr2: 00477758
double *dptr2;
Notes: 256
2006 C++ Course Handouts January 2006
Register class
#include <stdio.h>
register x=0, var=0; // register class
int y=0, count=0; // signed integers
int main(void)
{
for (x=0; x<10000; x++) Register access 2 cycles
count++;
for (y=0; y<10000; y++) Memory access 12 cycles
count++;
. Each cycle is one tick of the
. clock.
return(0);
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 513
Register class
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 514
Notes: 257
2006 C++ Course Handouts January 2006
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 515
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 516
Notes: 258
2006 C++ Course Handouts January 2006
int main(void)
{
.
. Other C++ Code
.
}
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 517
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 518
Notes: 259
2006 C++ Course Handouts January 2006
Summary
Boolean Expressions
Enumeration Types
Bitwise Operators
Register Class
Volatile & Extern
3/4/2006 Jim Adams C++ Presentation -- Copyright 2004, 2005, 2006 519
Notes: 260