Professional Documents
Culture Documents
Chapter 3
Algorithm
A well ordered collection of unambiguous and effectively
computable operations that produces a result and halts in a
finite amount of time.
Enumeration Type
A type whose values are defined by a list of constants of type
int.
Chapter 4 and 5
Top-Down-Design
Break down the task to be accomplished into subtasks,
decompose each of these subtasks into smaller subtasks, etc. Also called "Stepwise refinement or divide and conquer."
Functions
-Value of a function is an argument.
-Function Call An expression consisting of the function name
followed by arguments enclosed in parentheses.
Type Cast
Changes an int into a double:
static_cast<double>(number/variable);
Function Declaration
-Describes how the function is called at the top of the program
before main(). Required to appear prior to the call to a function
whose definition has not yet appeared.
Call by Value
Argument values are plugged into the function's parameters.
Just the values, not the variables themselves. The formal
parameter is a local variable that is initialized to the value of
the corresponding argument.
Call-by-Reference
The argument variables are plugged into the functions
parameters, not the values. The argument variable is
substituted in for the formal parameter so that any change that
is made to the formal parameter is actually made to the
argument variable.
Black Box
Anyone who uses a function should not be required to know the
contents of the functions to see how it works, but rather that it
will do what it is meant to do when called.
-Also called "information hiding".
-Writing and using functions as if they were black boxes is also
called "procedural abstraction."
Void Functions
Used when you want the program to output some results of a
calculation, but not to return a value for the rest of the program
to use.
Formal Parameters
For a function are listed in the function declaration and are used
in the body of the function definition. It is a blank placeholder
that is filled with something when the function is called.
Precondition
States what is assumed to be true when the function is called.
Postcondition
Describes what the function actually does.
Chapter 10
Structure
An object without any member functions. Though it carries
member variables and can hold data values.
Member Variables
Specified by giving the name of the structure variable followed
by a period, then the member name. ex: account.balance.
Class
A data type who variables are objects. Each object as a variable
has member functions, as well as the ability to hold data values.
Scope resolution operator
Used to tell what a member function is a member of. ex.
DayOfYear::output().
An accessor function for a member variable is a non-void
function that returns a member variable
// Constructors //
int main()
{
Cat myCat;
cout << "My cat is "
<< myCat.getState()
<< endl;
cout << "What is the cat's name?" << endl;
string name;
cin >> name;
// In main
myCat.setName(name);
// Name in the cat
object
Cat cat2("whiskers", "tabby", "eating");
Cat anotherCat("Chairman Meow", "Siamese", "plotting");
anotherCat.attack(cat2);
cout << anotherCat.getName() << " is " <<
anotherCat.getState() << endl;
cout << cat2.getName() << " is " << cat2.getState() <<
endl;
//cat2.name = "Captain Whiskers";
public
cat2.setName("Captain Whiskers");
system("pause");
return 0;
}
Cat::Cat()
// Default constructor
{
state = "sleeping";
name = "Snowball";
breed = "stray";
}
Cat::Cat(string aName, string aBreed, string init)
{
state = init;
name = aName;
breed = aBreed;
}
// Functions for class //
void Cat::startEating()
// Scope resolution operator: "::"
{
state = "eating";
}
void Cat::setName(string aName)
{
name = aName;
}
string getName()
{
return name;
}
void Cat::attack(Cat target)
{
state = "attacking";
target.state = "defending";
}
// Default for class is PRIVATE
Struct example
struct CDAccount
{
double balance;
double interest_rate;
int term;
};
void get_data(CDAccount& the_account);
int main()
{
CDAccount account;
get_data(account);
double rate_fraction, interest;
rate_fraction = account.interest_rate / 100.0;
interest = account.balance * rate_fraction * (account.term /
12.0);
account.balance = account.balance + interest;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "When your CD matures in "
<< account.term << " months,\n"
<< "it will have a balance of $"
<< account.balance << endl;
}
void get_data(CDAccount& the_account)
{
cout << "Enter the account balance: $";
cin >> the_account.balance;
cout << "Enter account interest rate: ";
cin >> the_account.interest_rate;
cout << "Enter the number of months until maturity\n"
<< "(must be 12 or fewer months); ";
cin >> the_account.term;
}
Class Example
class DayOfYear
{
public:
void output(); //Member function declaration
int month;
int day;
};
int main()
{
DayOfYear today, birthday;
cout << "Enter today's date:\n ";
cin >> today.month;
cout << "Enter the day of the month: \n";
Switch Example
int main()
{
char grade;
cout << "Enter your midterm grade and press Return: ";
cin >> grade;
switch (grade)
{
case 'A':
case 'a':
cout << "Excellent. "
<< "You do not need to take the final." << endl;
break;
case 'B':
case 'b':
cout << "Very good. ";
grade = 'A';
cout << "Your midterm grade is now " << grade
<< endl;
break;
case 'C':
case 'c':
cout << "Passing. ";
break;
case 'D':
case 'd':
case 'F':
case 'f':
cout << "Not good. "
<< "Go study." << endl;
break;
default:
cout << "That is not a possible grade." << endl;
}
cout << "End of program." << endl;
Descending Stars
Int num;
cin >> num;
for(int i = num; i >= 1;i--)
{
for(int j = 1; j <= i; j++)
{
cout << "*";
}
cout << endl;
}
Print 1-100 divisible by n
for(int i = 0;i <= 100; i++)
{
if((i%4 == 0) && !(i%3 == 0))
{
cout << i << endl;
Chapter 6: I/O
Opening a file: in_file.open("file.dat"); or declare the file to
open as a string and use cin>> and convert to a c_str(). With
in_file.open(file.c_str());
.setf(ios::fixed); : uses fixed point rather than exponential
.setf(ios::showpoint); : show decimal point
Manipulators: apply only to the next item; use #include
<iomanip>
-Streams may be passed as an argument to a void input
function; must be passed by reference
Extraction operator ">>": skips whitespace characters; can
use a loop to pick up all numerical data.
in_stream.get(next): reads one character and advances
position in stream
out_stream.put(char. expression): writes one character to
the stream
getline(in_file, next): reads entire line.
eof(): use a loop to read the entire file; while(! in_file.eof())
-Don't use eof() with numeric data
-Dont use >> with text data
Inheritance: a child class inherits member functions from its
parent; while a child class can have its own unique member
functions
Object: variable that has functions associated with it.
Class: a type whose variables are objects
ifstream , ofstream are examples of classes.
Chapter 7: Arrays
Array declaration: char name[5]; or int score[5] =
{1,2,3,4,5}; int score[] = {1,2};
Indexed variables: the individual variables that make up an
array.
Contiguous storage: One double takes up 8 bytes of storage;
double list[5] will use 40 consecutive bytes of memory storage
-cin >> list[5] is illegal.
-Passing an array in a function ex: void doubler(double a[],
int size);
doubler(list, 5); arrays are always passed to a function using
pass by array
-Array parameters are always passed by reference; if you
do not want the array to change, use const; ex: void
change(const int a[], int size)
Declaring 2d array: array1[2][6] = 7; Saves 7 as the spot in
that array grid.
-char arrays can use << or >>
}
}
Ascending Numbers
int i = 1;
do{
cout << i << endl;
i++;
}while(i <= 100);
for(int i = 1;i <=100;i++)
{
cout << i << endl;
}
FizzBuzz
for(int i = 0;i <= 100; i++)
{
if((i%3 == 0) && (i%5 == 0))
{
cout << "FizzBuzz" << endl;
}
else if(i%3 == 0)
{
cout << "Fizz" << endl;
Chapter 11: Friend Functions
Operator overloading function declaration:
friend bool operator == (const patient& one, const
patient& two);
Why is this done: So you dont necessarily need to call any
accessor functions to find data from the parameter since the
overloaded operator is a member of the class and has full
access to all private data.
Header: bool operator == (const patient& one, const patient&
two)
-The operator is a friend of the patient class; declaration
appears in the class definition, though in the header there is no
scope resolution operator, or mention of the class itself.
Rules for operator overloading or restrictions:
-Cannot create new symbols; cannot change the number of
arguments; cannot change precedence; at least one parameter
must be a class type; cannot overload (::) scope resolution or (.)
dot operator.
Overloading extraction operators:
Declaration: friend ostream& operator <<(ostream& outs,
const patient& one);
Algorithm
A well ordered collection of unambiguous and effectively
computable operations that produces a result and halts in a
finite amount of time.
Examples
Check to make sure file opens
file_in.open(in_file_name);
if (file_in.fail())
{
cout << "Input file opening failed." << endl;
exit(1);
}
Loop to get files from ifstream
getline(fin, bank_name);
getline(fin, account_num);
fin >> balance;
while (! fin.eof())
{
fin >> next;
if (fin.eof())
break;
Max = array[0];
For(int i = 0; i < 10; i++)
{
if(array[1] > max)
Max = score[i];
}
For(int i = 0; i < 10; i++)
{
Sum = array[i] + sum;
}
Double avg = 0;
Avg = sum/10.0;
Cout << sum << endl;
Cout << avg << endl;
Cout << max << endl;
Passing an array in a function
int list[5];
void doubler(double a[ ], int size)
{
for (int i = 0; i < size; i++)
{
a[i] = 2*a[i];
}
}
// to call:
doubler(list, 5);
Ascending Stars
int num;
cin >> num;
for(int i = 1; i <= num; i++)
{
for(int j = 1; j <= i; j++)
{
cout << "*";
}
cout << endl;
}
Descending Stars
Int num;
cin >> num;
for(int i = num; i >= 1;i--)
{
for(int j = 1; j <= i; j++)
{
cout << "*";
}
cout << endl;
}
Ascending Numbers
int i = 1;
do{
cout << i << endl;
i++;
}while(i <= 100);
empty list, you use the pointer NULL. Just set head = NULL;
Iterator: A construct that allows you to cycle through the data
items stored in a data structure so that you can perform
whatever action you want on each data item.
Ex: Node_Type *iter;
for( iter = Head; iter != NULL; iter = iter->link)
cout << (iter->data);
Stack: A data structure which is LIFO(Last in first out).
Queue: A stack/data structure which is FIFO(First in First out).
Ch. 14 Recursion
Stack overflow: An error message which signifies that some
function call has produced an excessively long chain of
recursive calls. It means the stack has reached its maximum
size with the memory allocated for it.
Ch. 15 Inheritance and Polymorphism