You are on page 1of 15

Ch.

2 introduction to C++
2.1 parts of a program

-example of simple program:


//This is a comment
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World" << endl;
cout << "Second line";
return 0;
}
-special characters
//
Marks the beginning of a comment.
#
Marks the beginning of a preprocessor directive.
<>
Encloses a filename when used with the #include directive.
()
Used in naming a function, as in int main().
{}
Encloses a group of statements, such as the contents of a function.
""
Encloses a string of characters, such as a message that is to be printed on the screen.
;
Marks the end of a complete programming statement.
2.2 the cout object
-common escape sequences. They go within the text you are displaying in the cout object.

\n
Newline
Causes the cursor to go to the next line for subsequent printing.
\t
Horizontal tab
Causes the cursor to skip over to the next tab stop.
\a
Alarm
Causes the computer to beep.
\b
Backspace
Causes the cursor to back up, or move left one position.
\r
Return
Causes the cursor to go to the beginning of the current line, not the next line.
\\
Backslash
Causes a backslash to be printed.
\'
Single quote Causes a single quotation mark to be printed.
\"
Double quote Causes a double quotation mark to be printed.
2.4 variables and literals
-to create a variable, do: int variable_name; (int means variable_name will hold an integer) and then assign it what
it holds, e.g., variable_name = 5;.
-to print a variable, do: cout << "The value is" << variable_name;
-a literal is a piece of data that is written directly into a program's code. Examples include the numebr 5 in the ex.
above (integer literal) and text written on the screen (string literal).
2.5 identifiers
-an identifier is a progammer-defined name that represents an element in a program.
-identifiers should be named such that they make sense (like velocity not vel), and not begin with a number.
2.6 integer data types
-integer data types:
short int
2 bytes
-32,768 to 32,767
unsigned short int
2 bytes
0 to 65,535
int
4 bytes
-2,147,483,648 to 2,147,483,647
unsigned int
4 bytes
0 to 4,294,967,295
long int
4 bytes
-2,147,483,648 to 2,147,483,647
unsigned long int
4 bytes
0 to 4,294,967,295
long long int
8 bytes
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned long long int
8 bytes
0 to 18,446,744,073,709,551,615
-these can be shortened by removing the word "int" from the name.
-unsigned data types can only store nonnegative values.
-you can define multiple variables that have the same data type on the same line separated with commas, e.g., int
length, width.
-if u want 2 change, say, an int to long int, place an L after the #, e.g: long amount; /*new line*/ amount = 32L;.
W/out the L, 32 would b treated as an int, not a long int.
2.7 the char data type
-it's used to store individual characters, must use single quotes, e.g.: char variable_name; /*new line*/
variable_name = 'g';
-it's actually stored as an integer data type, so A means 65 and B means 66, etc.
2.8 the string class
-to create a string type variable, first include the string header file: #include <string> and then do as expected:
string variable_name; /*new line*/ variable_name = "insert_string_here"
2.9 floating-point data types
-stored in scientific notation, e.g., 247.91 is 2.479E2. 2.47 is called the mantissa and 2 is the power.
-floating point data types:

Single precision
float
4 bytes
Numbers between 3.4E-38 and 3.4E38
Double precision
double
8 bytes.
Numbers between 1.7E-308 and
1.7E308
Long double precision
long double 8 bytes
Numbers between 1.7E-308 and 1.7E308
-you can force a literal to be stored as a float by appending the letter F or f to the end of the #, like with integers in
2.6. Use L for long doubles.
-if you do int number; /*new line*/ number = 7.5 then number = 7 not 7.5 b/c it's an integer.
2.10 the bool data type
-expressions tht have a true or false value are called Boolean expressions. They're useful for evaluating conditions
that are either true or false. Ex:
int main()
{
bool boolValue;
boolValue = true;
cout << boolValue << endl;
boolValue = false;
cout << boolValue << endl;
return 0;
}
Program Output:
1
0
2.11 determing the size of a data type
-use sizeof(____) to find the number of bytes of a data type.
2.12 variable assignments and initialization
-an assignment statement is when a value is stored in a variable, like units_sold = 12. The = is the assignment
operator. Operators perform operations on data. The data that the operators work with is called operands, e.g.,
units_sold and the 12. The operand on the left is called the lvalue and the right is the rvalue. lvalues represent is
something that identifies a place in memory whose contents may be changed and a rvalue is any expression that
has a value. So the assignment statement takes the value in the rvalue and puts it in the memory location of the
object identified by the lvalue.
-you can initialize variables as so: int month = 2, day = 28, year. Initialize is when you give the variable a data type
(like int) and give the variable a value (like 2 and 28). You can do multiple variables at a time like in the example.
You can define some but not initialize all of them too.
-the auto key word simplifies the syntax of declarations, most useful for complex declarations. Ex: auto
interest_rate = 12.0 (auto makes the variable here a double automatically).
2.13 scope
-the scope of a variable is the parts of a program where the variable may be used, e.g., can't be used until it's
defined.
2.14 arithmetic operators
-3 types of operators: unary, binary, & ternary. Names show # of operands. -5 is unary b/c of negation operator (-).
Only 1 ternary operator. Binary operators:
Operator
Meaning
Example
+
Addition
total = cost + tax;

Subtraction
cost = total tax;
*
Multiplication tax = cost * rate;
/
Division
salePrice = original / 2;
%
Modulus
remainder = value % 3;
-the only way for a division operation to return a floating-point value is for one of the operands to be a floatingpoint data type.
2.15 comments
-use //text for a single-line comment and /*text*/ for a multi-line comment.
2.16 named constants
-a named constant is like a variable but cannot be changed while the program is running is it's content is read-only.
Make one by adding "const" before initializing a variable like: const double INTEREST_RATE = 0.069. The name
should be in all caps. Useful so that programs are more self-documenting and so that changes to that one variable
can be changed with ease. Ex: amount = balance * 0.069 changes to amount + balance * INTEREST_RATE. So if
INTEREST_RATE changes in the program, one line is changes as opposed to many.
2.17 programming style
-to make a statement multi-line, just indent it. If you're multi-lining a string being cout-ed, then do:
cout << "The Fahrenheit temperature is "
<< fahrenheit
<< " and the Celsius temperature is "

<< celsius
<< endl;
Ch. 3 expressions and interactivity
3.1 the cin object
-use the cin object when you need input from user, like so:
int length;
cout << "What is the length of the rectangle? ";
cin >> length;
-can input multiple values like so:
cout << "Enter the length and width of the rectangle separated by a space.\n";
cin >> length >> width;
-it can handle multiple values that are different data types too.
3.2 mathematical expressions
-can put operations in the cout object, like: cout << (numerator / denominator) << endl;
-to do exponents, do: area = pow(4.0, 2.0);
pow is a function, the first argument is the base and the
second argument is the exponent
-when the pow function is used, do 3 things: include the cmath header file (#include <cmath>), the arguments r
doubles, and the variable used to store pow s return value should be defined as a double.
3.3 type conversion
-there are three rules for when different data types interact with each other (like in math):
-Rule 1: chars, shorts, and unsigned shorts are automatically promoted to int.
-Rule 2: when an operator works with two values of different data types, the lower-ranking value is promoted
to the type of the higher-ranking value.
-Rule 3: when the final value of an expression is assigned to a variable, it will be converted to the data type
of that variable.
-when dividing integers, the result will always be an integer. To fix, make an operand a floating-point data type.
3.4 overflow and underflow
-when a variable is assigned data that is too large for it's data type or too small, then overflow or underflow occurs.
This will produce errors.
3.5 type casting
-type casting lets you manually change data types. Set-up is as follows: static_cast<DataType>(Value). Value is the
variable or literal value that you want to change.
-can use it to change an integer to its character equivalent and vice versa.
3.6 multiple assignment and combined assignment
-multiple assignment: a = b = c = d = 12;
-combined assignment operators:
More Complex Examples (these two
columns)
Operator
Example Usage
Equivalent to
Example Usage
Equivalent to
+=
x += 5;
x = x + 5;
x += b + 5;
x = x + (b + 5);
=
y = 2;
y = y 2;
y = a * 2;
y = y (a * 2);
*=
z *= 10;
z = z * 10;
z *= 10 c;
z = z * (10 c);
/=
a /= b;
a = a / b;
a /= b + c;
a = a / (b + c);
%=
c %= 3;
c = c % 3;
c %= d 3;
c = c % (d 3);
3.7 formatting option
-use stream manipulator setw(# of spaces) to specify the min # of spaces for output (use #include <iomanip> for
setw), example: value = 23; cout << setw(5) << value; <- this will display 3 spaces and then 23, making 5 total
spaces. Useful for making columns. Data is right-justified automatically.
-use setprecision(# of #'s) manipulator to specify the number of sig figs (use #include <iomanip> for setw), e.g.:
quotient = 4.91877; cout << setprecision(5) << quotient << endl;
<- displays the number 4.9188
-the stream operator, fixed, forces the cout to print digits in fixed-point notation. Example:
cout << setprecision(2) << fixed;
cout << "Day 1: " << setw(8) << day1 << endl;
cout << "Day 2: " << setw(8) << day2 << endl;
cout << "Day 3: " << setw(8) << day3 << endl;
cout << "Total: " << setw(8) << total << endl;
-the first line sets the percision to 2 places after the decimal point only b/c the fixed manipulator is
there.
-showpoint lets you show the trailing zeros for a number, ex: double x = 123.4; cout << setprecision(6) <<
showpoint << x << endl;
-left and right let you change the justification of the output. Ex: cout << left << setw(10) << x << endl;
3.8 working with characters and string objects
-since cin messes up w/ strings, we use the getline function instead. Example:
string name;
cout << "Please enter your name: ";

getline(cin, name);
cout << "Hello " << name;
-the simplest way to get one character of input is with: char ch; cout << "Type a character and press Enter: "; cin
>> ch;
-when you want something to happen by the using pressing enter, space, or tab, then use cin.get();
-use cin.ignore(); to have the program ignore one character space. Useful for situations like this:
char ch; // Define a character variable
int number; // Define an integer variable
cout << "Enter a number: ";
cin >> number; // Read an integer
cin.ignore();
cout << "Enter a character: ";
ch = cin.get(); // Read a character
cout << "Thank You!\n";
-without the cin.ignore, the cin.get() reads the \n character that's created when you hit the enter key after
typing in an integer, so the cin.ignore skips this character.
-cin.ignore(n,c); can skip multiple characters until it reads the c, which is any character you want (even \n). n is the
# of characters to skip. Whichever comes 1st.
-2 find length of string stored in variable, do: string state = "Texas"; int size = state.length();
[stores length
in size variable]
-to concatenate (join) two strings, do: joined_string_variable = string_variable + other_string variable;
3.9 more mathematical library functions
-more functions:
Function
Example
Description
abs
y = abs(x);
Returns the absolute value of the argument. The argument and the return value are
integers.
cos
y = cos(x);
Returns the cosine of the argument. The argument should be an angle expressed in
radians. The return type
and the argument are doubles.
exp
y = exp(x);
Computes the exponential function of the argument, which is x . The return type and
the argument are
doubles.
fmod
y = fmod(x, z);
Returns, as a double , the remainder of the first argument divided by the
second argument. Works like the
modulus operator, but the arguments are doubles.
(The modulus operator only works with integers.) Take
care not to pass zero as the
second argument. Doing so would cause division by zero.
log
y = log(x);
Returns the natural logarithm of the argument. The return type and the argument are
doubles.
log10
y = log10(x); Returns the base-10 logarithm of the argument. The return type and the argument are
doubles.
sin
y = sin(x);
Returns the sine of the argument. The argument should be an angle expressed in
radians. The return type and
the argument are doubles.
sqrt
y = sqrt(x); Returns the square root of the argument. The return type and argument are doubles.
tan
y = tan(x);
Returns the tangent of the argument. The argument should be an angle expressed in
radians. The return type
and the argument are doubles.
-random #'s: cstdlib header file: y = rand(); this is pseudorandom, for real random, use srand()
-to have a random # made within a range, do:
const int MIN_VALUE = # of your choosing;
const int MAX_VALUE = # of your choosing;
y = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
Ch. 4 making decisions
4.1 relational operators
-realtional operators:
Relational Operators Meaning
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
==
Equal to
!=
Not equal to
-if a relational expression is true, it returns a 1, if false, a 0. So if you do: bool vairable; variable = (5 < 6); then
variable holds the number 1.
4.2 if statement
-set up like so:
[if the expression is true, then the statements underneath are executed, if not,
they are skipped]
if ( expression )
{

statement;
...

}
-when using == to compare floating-point #'s, an error occurs in that the #'s are equal but they are slightly
different (+/- 0.000000000001 for ex <-made up # to show point). To prevent round-off errors, you should use
greater-than and less-than comparisons with floating-point numbers.
-anything other than 0 is true for the if statment. That means anything put into the expression, so long as it doesn't
equal zero, will execute the statements below.
4.4 if/else statement
-set up like so:
[means if the expression is true, it will do the first set of statements, if it's false, it will
do the statements under "else."]
if ( expression )
{
statements
}
else
{
statements
}
-you can nest if statements inside one another.
4.6 if/else if statement
-set-up like so:
[works like so: if 1st expression is true, it does statements, if false, goes to expression 2. If
this is false, goes to 3rd and so on]
if ( expression_1 )
{
statements
}
else if ( expression_2 )
{
statements
}
[Insert as many else if clauses as necessary]
else
{
statements
}
-useful to avoid nested if statements. The last else clause is optional.
4.8 logical operators
Operator
Meaning
Effect
&&
AND
Connects two expressions into one. Both expressions must be true for the overall
expression to be true.
||
OR
Connects two expressions into one. One or both expressions must be true 4 the overall
expression to be true.
!
NOT
The ! operator reverses the "truth" of an expression. It makes a true expression false,
and a false one true.
-Ex: if (income >= MIN_INCOME || years > MIN_YEARS)
-Ex of NOT:
if (!(temperature > 100))
[equivalent to: is the temperature not
greater than 100?]
cout << "You are below the max temperature.\n";
[if temp > 100 is true, NOT makes it false
and vice versa]
-useful to avoid nested if statements.
4.11 input validation
-can use if/else statements to validate user input.
4.12 comparing characters and strings
-can use if statements and such to compare characters and strings together.
4.14 switch statement
-A branch occurs when one part of a program causes another part to execute. The if/else if statement allows your
program to branch into one of several possible paths. It performs a series of tests (usually relational) and branches
when one of these tests is true. The switch statement is a similar mechanism. It, however, tests the value of an
integer expression and then uses that value to determine which set of statements to branch to. Set-up like so:
switch ( IntegerExpression )
{
case ConstantExpression :
// statements

break; // don't forget to add the break!


// case statements may be repeated as many times as necessary
default:
// statements

}
-IntegerExpression can be a variable of any integer data type (char too) or an expression whose value is of any of
the integer data type.
-ConstantExpression may be an integer literal or an integer named constant.
-if none of the case expressions match the switch expression, it does the statements under default.
-sometimes you want to omit the break if you want the choice to execute the statements following it in the other
cases.
-Example of a switch:
char choice;
cout << "Enter A, B, or C: ";
cin >> choice;
switch (choice)
{
case 'A':
cout << "You entered A.\n";
break;
case 'B':
cout << "You entered B.\n";
break;
case 'C':
cout << "You entered C.\n";
break;
default: cout << "You did not enter A, B, or C!\n";
}
-another example of how useful this fall through capability can be is when you want the program to branch to the
same set of statements for multiple case expressions. Like if you want it to recognize uppercase and lowercase
letters, do:
case 'a':
case 'A':
cout << "30 cents per pound.\n";
break;
Ch. 5 loops
5.1 increment and decrement operators
-can use variable++ and variable-- (or --variable and++variable) to increase or decrease variable by 1 rather than
variable += 1 or variable -= 1
-the prefix mode has the variable change value first and then the variable is the new number while the postfix
mode doesn't do anything to the variable at first (so that means any operation or anything that's done with the
variable will be done first) but then it changes the value. Example: cout << num++ since num will be displayed as
its original value and then added by 1.
5.2 while loop
-a while loop does a block of statements so long as a certain expression is true. Repeats forever until false. Set-up:
while (expression)
{
statements;
}
-is a pretest loop b/c it tests its expression before each iteration.
-a counter is a variable that regularly increments or decrements each time a loop iterates. Useful to control and/or
keep track of # of iterations.
5.3 while loops for input validation
-lets the user keep entering data until they enter it in properly, rather than terminating the program. Ex:
cout << "Enter a number in the range 1-100: ";
cin >> number;
while (number < 1 || number > 100)
{
cout << "ERROR: Enter a value in the range 1-100: ";
cin >> number;
}
5.5 do-while loop
-like an inverted while loop. Is a posttest loop b/c its expression is tested after each iteration. Set-up:
do
{

statements;
} while (expression);
-always does one iteration even if the expression is false. Useful for user-defined loops (user controls number of
iterations since programmer can't know it or ask).
5.6 for loop
-this loop is useful to use when you need to repeat something a specific # of times (count-controlled). Must have 3
elements:
1. It must initialize a counter variable to a starting value.
2. It must test the counter variable by comparing it to a maximum value. When the counter variable reaches its
maximum value, the loop terminates.
3. It must update the counter variable during each iteration. This is usually done by incrementing the variable.
-it's a pre-test loop. Set-up:
for (initialization; test; update)
{
statements;
}
-example:
for (count = 0; count < 5; count++)
{
cout << "Hello" << endl;
}
-can initialize in the initialization like so: for (int num = MIN_NUMBER; num <= MAX_NUMBER; num++). scope of
num is the loop.
5.7 running total
-A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the
running total is called an accumulator. Example:
int days;
double total = 0.0; // Accumulator, initialized with 0
cout << "For how many days do you have sales figures? ";
cin >> days;
// Get the sales for each day and accumulate a total.
for (int count = 1; count <= days; count++)
{
double sales;
cout << "Enter the sales for day " << count << ": ";
cin >> sales;
total += sales;
// Accumulate the running total.
}
5.8 sentinels
-if the user does not know the # of items in their list, use a sentinel. A sentinel is a special value that the user
enters to stop the loop at their choosing. Example:
int game = 1, // Game counter
points,
// To hold a number of points
total = 0;
// Accumulator
cout << "Enter # of points earned. Enter 1 when finished.\n\n";
cout << "Enter the points for game " << game << ": ";
cin >> points;
while (points != 1)
{
total += points;
game++;
cout << "Enter the points for game " << game << ": ";
cin >> points;
}
cout << "\nThe total points are " << total << endl;
5.10 nested loops
-a nested loop is a loop inside of another loop. Qualities of nested loops:
-an inner loop goes through all of its iterations for each iteration of an outer loop.
-inner loops complete their iterations faster than outer loops.
-to get the total number of iterations of a nested loop, multiply the number of iterations of all the loops.
Ch. 6 functions
6.1 purpose
-functions let you reuse code and make programs easier to create thru divide and conquer.

6.2 defining and calling functions


-When creating a function, you must write its definition. All function definitions have the following parts:
-Return type: A function can send a value to the part of the program that executed it. The return type is the
data type of the value
that is sent from the function.
-Name:
You should give each function a descriptive name. Should be verbs since functions do
something.
-Parameter list:
The program can send data into a function. The parameter list is a list of variables that
hold the values being passed to
the function.
-Body:
The body of a function is the set of statements that perform the functions operation. They are
enclosed in a set of
braces.
-example:
int main ()
[int is the return type, main is the name, the parameter list would be in the parenthese after
main, int main() is the
{
function header, statements in the function is the body]
cout << "Hello World\n";
return 0;
}
-functions that don't return a value are called void functions. Example:
void displayMessage()
{
cout << "Hello";
}
-functions you make should be created after the main() function, which you do with function prototyping
-to call a function, do: function(); in main().
6.3 function prototypes
-lets you call a function even if it's definition comes later. Set-up: return_type function_name (); <- include this
before calling the function, usually right before doing main().
6.4 sending data into a function
-the values that are passed into a function are called arguments, and the variables that receive those values are
called parameters. Example:
void displayValue(int);
int main()
{
displayValue(5);
return 0;
}
void displayValue(int num)
{
cout << "value is: " << num;
}
-5 is the argument while num is the parameter. When this executes, num = 5. The agrument could be 8+11 too, as
long as it equals an int.
-to have multiple arguments, separate w/ commas. Make sure you specify the data type before each parameter,
like in int num in above example.
6.5 passing data by value
-if data was made in the main function, and then another function modified the same variable, then the original
data is still the same when used in main again.
6.7 the return statements
-return; causes a function to stop immediately and returns to the statement that called the function. Useful for
errors, like making a function that divides by two numbers, and since the denominator can't be zero, using input
validation you can quit the function before the division.
6.8 returning a value from a function
-to create a value-returning function, choose what data type the return value will be, e.g., int main returns an int, 0.
int is the return type. Then have the last statement be return anything;
-commonly, you store the result of a function in a variable like so: variable = function(arguments);
-to initialize local variable w/ parameter values, turn:
int sum(int num1, int num2)
int sum(int num1, int num2)
{
{
int result;
int result = num1 + num2;
result = num1 + num2;
return result;
return result;
}
}
6.10 local and gobal variables
-if multiple functions need same constant value(s), then make these values global. Called global constants. Define
them b4 function prototypes.

6.11 static local variables


-if a function is called more than once in a program, the values stored in the functions local variables do not persist
between function calls. This is because the local variables are destroyed when the function terminates and are then
re-created when the function starts again. When you need a function to remember what value is stored in a local
variable between function calls, use static local variables. To create one, add the word static before initializing the
variable, e.g., static int variable = 5
6.12 default arguments
-a default argument is passed to the parameter when the actual argument is not in the function call. They're listed
in the function prototype. Ex: void showArea(double = 20.0, double = 10.0);
-can't override the second argument without having the first argument, but the opposite is true.
6.13 using reference variables as parameters
-by using a reference variable as a parameter, a function may change a variable that is defined in another function.
This lets the same variable be used in multiple functions. Called "pass by reference."
-reference variables are defined like regular variables, except w/ ampersand (&) in front of name. Ex:
void doubleNum(int &);
// function prototype
int main()
{
int value = 4;
cout << "In main, value is " << value << endl;
doubleNum(value);
cout << "Now value is " << value << endl;
return 0;
}
void doubleNum (int &refVar)
{
refVar *= 2;
}
-Output: In main, value is 4 \n Now value is 8
6.14 overloading functions
-two or more functions can have the same name, as long as their parameter lists are different (in terms of data
types and/or # of parameters).
6.15 exit() function
-The exit() function terminates a program. Use the cstdlib header file. Use like so: exit(0);
Ch. 7 arrays
7.1 arrays hold multiple values
-an array can hold multiple values (of the same data type), unlike a variable. Ex: int days[6]; "days" is the array name
and 6 is the # of elements.

7.2 accessing array elements


-each element in an array has a subscript, starts at 0 and ends at the # of elements minus 1. To add elements in an
array, do: days[0] = 31;
-subscripts are stored as variables, which lets you cycle through elements using loops, ex:
const int ARRAY_SIZE = 6;
int numbers[ARRAY_SIZE];
for (int count = 0; count < ARRAY_SIZE; count++)
numbers[count] = 99;
7.4 array initialization
-like variables, can make array like so: const int MONTHS = 12; int days[MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31,
30, 31, 30, 31};
-when creating an array that holds strings, put each string in quotation marks.
-don't have to provide values for each elements, can leave some elements empty.
-you don't have to provide the # of elements as long as you initilaize it, ex: double ratings[] = {1.0, 1.5, 2.0, 2.5,
3.0};
7.5 range-based for loop
-lets you not need a counter like in section 7.2. Set-up:
for ( dataType rangeVariable : array )
{
statements;
}
-data type has to match the data type of the elements in the array. Can use "auto" to automatically match it. Ex:
int numbers[] = { 3, 6, 9 };
for (int val : numbers)
cout << val << endl;
-the range-based for loop isn't capable of changing the elements within the array. To this you, just put an & in front
for the rangeVariable. Ex:
for (int &val : numbers)

{
cout << "Enter an integer value: ";
cin >> val;
}
7.8 arrays as function arguments
-how to get one element of an array from one function into another function:
void showValue(int);
int main()
{
const int SIZE = 8;
int numbers[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40};
for (int index = 0; index < SIZE; index++)
showValue(numbers[index]);
return 0;
}
void showValue(int num)
{
cout << num << " ";
}
-to change the above program to pass the entire array into the function, put this in main() to replace the for loop:
showValues(numbers, ARRAY_SIZE); use this as the function prototype: void showValues(int [], int); and the second
function becomes:
void showValues(int nums[], int size)
{
for (int index = 0; index < size; index++)
cout << nums[index] << " ";
cout << endl;
}
7.9 two-dimensional array
-useful for when you have multiple sets of data. score[0][1] is the element in the 1st row and 2nd column. To
declare, do: double scores[3][4]; The 3 is the # of rows and the 4 is the # of columns.
-you typically use nested loops to cycle through each element in a 2D array. Ex:
for (div = 0; div < NUM_DIVS; div++)
{
for (qtr = 0; qtr < NUM_QTRS; qtr++)
totalSales += sales[div][qtr];
}
// Adds all the numbers in the array
-to initialize a 2D array, do: int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}}; This looks like so:
Column 0
Column 1
Row 0
8
5
Row 1
7
9
Row 3
6
3
-if you want to pass a 2D array into a function, then the parameter type must have the # of columns. Ex:
showArray(table2, TBL2_ROWS);
// This is the call of the function showArray
void showArray(const int numbers[][COLS], int rows)
//This is the definition of the showArray function
7.10 more than 2 dimension arrays
-when writing functions that accept multi-dimensional arrays as arguments, all but the first dimension must be
explicitly stated in the parameter list.
arrays and objects
-To get to the second student's score1, you need to get to the second element in the array, and extract the score
from that element in the array, using the notation st[1].getScore().
-The following code sets up an array of objects in code:
int main()
{
Student mystudents[5];
for (int i=0; i<5; i++)
{
mystudents[1];
}
return 0;
}
-Line 3 sets up an array called mystudents with 5 elements in it. The datatype of the array is Student, our
object type. Each is instantiated with the default constructor.

-As with any other array, this array is accessed via a for loop. As the ith element is processed, when the .
operator is used, the intellisense drop-down box correctly displays the object member functions, and the printData
function for that element within the array can be accessed.
-The following code sets up a 5 element array, but invokes the parameterized constructor:
int main( )
{
Student mystudents[5] = { Student("Maya", 10),
Student(),
Student("Amy") ,
Student(),
Student("Dave", 98)};
for(int i=0; i < 5; i++)
{
mystudents[i].printData();
}
return 0;

}
-Object variables can be passed as function parameters. They are passed by value, as other C++ variables. They
may be passed by reference or by pointer value.
-Arrays of struct variables are built similarly.
Passing object variables to a function by value
-Consider a function called printSt that prints out the struct variable passed to it. The function is invoked as
follows:
Student s1;
//statements to populate s1
printSt (s1);
void printSt(Student a)
{
cout << a.printData()<<endl;
}
-Consider a function called fillSt which takes in a object variable and then modifies its contents. It fills the object
variable with values obtained from the user. Since the function needs to modify the incoming parameter, it is
treated as a reference parameter.
Student s1;
fillSt(s1);
//statements to populate s1 I think
void fillSt(stType &st)
{
string name;
int score;
cout << "enter name : ";
cin >> name;
st.setName(name);
cout << "enter score : ";
cin >> score;
st.setScore(score);

}
Ch 8 searching and sorting an array
-use notes.
Ch. 13 classes
13.1 objects and procedures
-objects contain data (or attributes) and functions that operate on that data (methods or member functions). Code
outside the object only interacts with the methods, not the data in it.
-a class is the blueprint of an object--a class creates instances of as many objects as you want.
13.2 intro to classes
-to make a class, do:
class ClassName
{
declarations; // declarations are the variables and functions
};
// don't forget the semicolon!
-Ex:

class Rectangle
{
private:
double width;
double length;
public:
void setWidth(double);
void setLength(double);
double getWidth() const;
double getLength() const;
double getArea() const;
};
-In the declaration above, the member variables width and length are declared as private , which means they can
be accessed only by the classs member functions. The member functions, however, are declared as public, which
means they can be called from statements outside the class. If code outside the class needs to store a width or a
length in a Rectangle object, it must do so by calling the objects setWidth or setLength member functions.
Likewise, if code outside the class needs to retrieve a width or length stored in a Rectangle object, it must do so
with the objects getWidth or getLength member functions. These public functions provide an interface for code
outside the class to use Rectangle objects.
-when the key word const appears after the parentheses in a member function declaration, it specifies that the
function will not change any data stored in the calling object.
-to complete the Rectangle example above, you would make the function definitions outside of the class
declaration, ex:
void Rectangle::setWidth(double w)
{
width = w;
}
void Rectangle::setLength(double len)
{
length = len;
}
double Rectangle::getWidth() const
{
return width;
}
double Rectangle::getLength() const
{
return length;
}
double Rectangle::getArea() const
{
return width * length;
}
-general format for the function of the function header of any member function defined outside the declaration of a
class:
ReturnType ClassName :: functionName ( ParameterList )
-It is a common to make all of a classs member variables private and to provide public member functions for
accessing and changing them. This ensures that the object owning the member variables is in control of all
changes being made to them. A member function that gets a value from a classs member variable but does not
change it is known as an accessor . A member function that stores a value in member variable or changes the
value of member variable in some other way is known as a mutator . In the Rectangle class, the member functions
getLength and getWidth are accessors, and the member functions setLength and setWidth are mutators. Some
programmers refer to mutators as setter functions because they set the value of an attribute, and accessors as
getter functions because they get the value of an attribute.
-accessors (getter functions) typically have the const after the parameter name
13.3 defining an instance of a class
-to create an instance of a class, do: ClassName objectName; Can create multiple instances.
-ex of a program using objects and classes:
#include <iostream>
using namespace std;
class Rectangle
{
private:
double width;
double length;

public:

};

void setWidth(double);
void setLength(double);
double getWidth() const;
double getLength() const;
double getArea() const;

void Rectangle::setWidth(double w)
{
width = w;
}
void Rectangle::setLength(double len)
{
length = len;
}
double Rectangle::getWidth() const
{
return width;
}
double Rectangle::getLength() const
{
return length;
}
double Rectangle::getArea() const
{
return width * length;
}
int main()
{
Rectangle box; // Define an instance of the Rectangle class
double rectWidth; // Local variable for width
double rectLength; // Local variable for length
// Get the rectangle's width and length from the user.
cout << "This program will calculate the area of a\n";
cout << "rectangle. What is the width? ";
cin >> rectWidth;
cout << "What is the length? ";
cin >> rectLength;
// Store the width and length of the rectangle in the box object.
box.setWidth(rectWidth);
box.setLength(rectLength);
// Display the rectangle's data.
cout << "Here is the rectangle's data:\n";
cout << "Width: " << box.getWidth() << endl;
cout << "Length: " << box.getLength() << endl;
cout << "Area: " << box.getArea() << endl;
return 0;
}
-In the Rectangle class, the getLength and getWidth member functions return the values stored in member
variables, but the getArea member function returns the result of a calculation. You might be wondering why the
area of the rectangle is not stored in a member variable, like the length and the width. It's b/c it could potentially
become stale. When the value of an item is dependent on other data and that item is not updated when the other
data are changed, it is said that the item has become stale. If the area of the rectangle were stored in a member
variable, the value of the member variable would become incorrect as soon as either the length or width member
variables changed.

-can do input validation in mutator function.


13.5 using files to organize OOP
-store class declarations in header files. This is called a class specification file. Name of file is the same as the class
with .h extension.
-function definitions are stored in a .cpp file. Called class implementation file. Name of file is the same as the class.
-any program that uses the class should #include the class's header file. The class's .cpp file (that holds the
functions) should be compiled and linked with the main() program.
-ex of Rectangle.h:
// Specification file for the Rectangle class.
#ifndef RECTANGLE_H
#define RECTANGLE_H
// Rectangle class declaration
class Rectangle
{
private:
double width;
double length;
public:
void setWidth(double);
void setLength(double);
double getWidth() const;
double getLength() const;
double getArea() const;
};
#endif
-ex of Rectangle.cpp:
#include "Rectangle.h"
// Needed for the Rectangle class
#include <iostream>
using namespace std;
[insert functions here]
-ex of the actual program w/ main(). All you do is do #include "Rectangle.h" at the top, compile the function file w/
this file, and then have main() as normal (from the huge example program above).
13.6 inline member functions
-to increase a program's performance, you can have the functions of a class in the class specification file (in the
public section). When you do this, then there is no need to do the "Rectangle::" part of the function header.
Commonly done with the setters and getters since they're small.
13.7 constructors
-it's a function that is automatically called when an instance is created. Named same as class. Ex:
class Demo
{
public:
Demo(); // Constructor
};
Demo::Demo()
{
cout << "Welcome to the constructor!\n";
}
-format: ClassName :: ClassName ( ParameterList )
-the purpose is to initialize values for the object so that it isn't automatically filled with garbage. Like for the
Rectange example, you'd set width and length to 0.0.
13.8 passing arguments to constructors
-When the object will accept data, then the constructor can take it in so that you don't need to initialize the values
as described above nor do you have to leave it empty to be filled with garbage. Because the constructor is
automatically called when a Rectangle object is created, the arguments are passed to the constructor as part of the
object definition. Ex:
// In the specification file:
public:
Rectangle(double, double);
// In the implementation file:
Rectangle::Rectangle(double w, double len)
{
width = w;
length = len;
}
-to have default arguments (e.g. if you don't include an argument than a predetermined value is passed

automatically), then just specify the value in the specification file like so:
public:
Sale(double cost, double rate = 0.05)
{ itemCost = cost; taxRate = rate; }
13.9 destructors
-a destructor is a member function that is automatically called when an object is destroyed.
-same name as the class, preceded by a tilde character (~)
13.10 overloading constructors
-can have multiple constructors, so long as they have different parameter lists (data types and/or different # of
items). A constructor without any parameters is the default constructor, of which there can only be one.
-when you need several different ways to perform the same operation, then you can overload functions in a class
too.
13.11 private functions
-a class will contain one or more member functions that are necessary for internal processing, but should not be
called by code outside the class. To do this, declare the function as private by putting it in the private declaration.
13.12 arrays of objects
-can create an array that holds object instances, like so:
const int ARRAY_SIZE = 40;
InventoryItem inventory[ARRAY_SIZE];
//name of array is inventory
-to define an array of objects and call a constructor that requires arguments, you must specify the arguments for
each object individually in an initializer list. Example:
InventoryItem inventory[] = {"Hammer", "Wrench", "Pliers"};
-If a constructor requires more than one argument, the initializer must take the form of a function call. Example:
InventoryItem inventory[] = { InventoryItem("Hammer", 6.95, 12),
InventoryItem("Wrench", 8.75, 20),
InventoryItem("Pliers", 3.75, 10) };
-Objects in an array are accessed with subscripts, just like any other data type in an array. For example, to call the
setUnits member function of inventory[2] , the following statement could be used:
inventory[2].setUnits(30);
// this statement sets the units variable of inventory[2] to the value 30
13.16 UML
-UML (unified modeling language) is a standard method for graphically depicting an object-oriented system. Has
the class name on top, then the variables, and then the functions. + next to a variable/function is public and means private.

You might also like