You are on page 1of 34

Review of PIC 10A

Lesson 1
Pic 10B, Ricardo Salazar

Syllabus Highlights
Midterms:
Friday, January 29.
Friday, February 19.
From 10:00 to 10:50 am at MS 5200.

Final Exam:
Friday, March 18.
From 3:00 to 6:00 pm at MS 5200.

No makeup exams under any circumstances.


Homework assignments:
7 or 8 throughout the quarter. All of them worth 20 pts.
The lowest score will not count towards your grade.

Grading system
Your final score in the class will be the maximum of:
Schema A

25% Homework
20% Midterm 1
20% Midterm 2
35% Final

or
Schema B

25% Homework
30% Highest midterm
44% Final exam
1% Participation (details to be explained throughout the
quarter)

Assignments
The 'official' compiler we will use is the one available at
the PIC Lab: Currently Visual studio 2013.
You can use other compilers but
The usual: "I got 0 points but my program works on my
computer"
IS NOT A VALID EXCUSE.

If your assignment fails to compile you will be assigned


a temporary 0.
You then need to request a regrade (in writing).
Describe the changes needed so that it no longer fails
compilation.
Your maximum possible score will then be 16/20.

No late homework/email submission!!! (I'm serious)

10B. What about it?


10A was about learning 'vocabulary' (reserved words) as
well as grammar rules (syntax).
10B is about algorithms, data structures and style.
Algorithm: a self-contained step-by-step set of operations
to be performed [usually to solve a problem].
E.g: finding the minimum and maximum of a list.

Data structure: a particular way of organizing data in a


computer so that it can be used efficiently.
E.g: vectors, arrays.

Programming style: a set of rules or guidelines used when


writing the source code for a computer program.
Good styling improves readability of code and minimizes
the effort needed to maintain code.

10B. What ? (cont)


We'll study several data structures because
There is no perfect structure.
They all have pros and cons.

The questions for 10B are:


How do we handle a large amount of data?
What is the most efficient way to implement our
algorithms?
How do we structure our classes/objects so that with very
minimal effort they can be extended/reused/improved.

Some of the topics we'll cover are a little technical


which means that some assignments will be 'boring'.
But I will try to 'spice things up' a bit, with backstories and
easter eggs.

Things you are expected to know


The basic C++ program.
/* ***************************************
remembered.cpp
Displays a greeting message to those
who passed away but are not forgotten.
*************************************** */
#include <iostream>
using namespace std;
int main(){
cout << "Hello! Land of the remembered.\n";
return 0;
}

something's missing
The comments (of course).

Things know (cont)


Basic libraries:

<iostream>
<iomanip>
<string>
<cmath>
<fstream>
<vector>

sqrt(pow(4,2)+pow(3,2))
cin
cout
myList.size()
name.length()
setw(10)

Some other non-basic libraries:

<ctime>
<cstdlib>
<algorithm>
"ccc_win.h"

ofstream fout;

Your turn! Fill in the boxes with statements associated to the corresponding libraries.

Things know (cont)


Data types.
Some random thoughts about them:
A variable/object cannot be used unless it is declared first.
Casting temporarily changes the type.
Different types have different operators available:
E.g: +, -, /, %, *, ++, +=, etc.

The most common data types:

int - integers (whole numbers). E.g: -3, 5, 2015.


double - decimals ('real' numbers). E.g: 3.14, 0.001, 3e-2.
bool - boolean (true/false). E.g: 2<3, 4.35*100 == 435
char - single character. E.g: 'A', '\n', '4'.
string - There are two types of 'strings':
False. Why???
[c] strings: an array of chars. E.g: "Manolo"
[c++] strings: objects with member functions.

Things know (cont)


Input/output
Basic input/output to/from the console.
cin >> x;

cout << "Hi there!\n";

cin/cout are objects.


They are instances of the particular classes istream and
ostream (defined in <iostream>).
Some useful tricks:
You can chain inputs/outputs:

cin >> aName >> aNumber >> aBool;


cout << "Hello " << aName << "!" <<

A full line can be read with getline

string s;
getline(cin, s);

endl;

Things know (cont)


Functions
General form:
type functionName(type param1, type param2, ){
-- STATEMENTS -}

Except for constructors, every function should have a


return statement.
Parameters can be passed
by value (a copy of the variable/object is made); or
by reference (the memory address of the original
variable/object is sent)

They are passed by value by default. Use & to change this.


E.g: void myFunction(int& a, int b);

Things know (cont)


Functions (cont)
Every function you write must be commented.
It is OK if the comments section is longer than the
function.
Describe the purpose, the parameters and the return type.

E.g:
/* *********************************************
multiplyTwoNumbers: Multiplies two doubles.
Parameters: doubles a and b to be multiplied.
Returns: the product of the parameters.
********************************************* */
double multiplyTwoNumbers(int a, int b){
return a*b;
}

Things know (cont)


File Input/Output (the <fstream> library is needed)
Reading and writing to files is similar than console I/O.
Files streams need to be created

ifstream fin; // fin = file in, just like cin


ofstream myFout; // fout is not mandatory

and associated with a files.

fin.open("file.txt"); // "file.txt" is a
// [c]-string
string fileName;
// fileName is a
cin >> fileName;
// [c++]-string
myFout.open( fileName.c_str() ); // <-- why?

Then we can use them just like cin/cout.

myFout << "My name is Maria Posada\n";


while ( fin >> word ) { // reads until the file ends

Exercise:
From the class syllabus:

Write a program (right now) that reads the scores from a file (see
the setup on the board), and computes the final score of a student.
Use at least one function,
pass at least one parameter by reference, and
save the final score in the file: grade.txt

My solution will be available at the ccle website.

Things know (Classes)


Recall: a class is a data type 'on steroids'.
it comes with special 'helper' functions.

An instance of a class is called an object.


string is an example of a class

value

string myFriend = "Joaquin";


class name

object name

The insert function is an example of a 'helper' function.


myFriend.insert(0,"Hola ");

Other examples include:


The Time and Employee classes;
The Graphics classes: Point, Circle, Line, and Message.

Things (class Interfaces)


A class declaration:

These functions create the object

These are the 'helpers'.


class ClassName {
They can handle the object
public:
without breaking it.
constructor declarations
Did you
member functions declarations
notice the
semi-colon?
private:
Internal values and functions.
data fields
};

Public fields are accessible outside of the class.


E.g: the length() function in the string class.

Private fields are only known locally (encapsulated).


Think of them as secret rooms in a big ol' castle.

Things (Product class)


If we want to rate different products based on their price
and a consumer score, we could create a Product class.
The declaration should look like this:
class Product {
public:
Product();
void read();
bool is_better_than(Product b) const;
void print() const;
private:
string name;
double price;
int score;
}; // <-- don't forget the semicolon

Things (Product class cont)


Then we have to implement the member functions.
The default constructor.
Product::Product(){price=1; score=0; name="no Item";}

Non default constructor.


Product::Product(string n, double p, int s){
name = n; price = p; score = s;
}

As well as other member functions.


Product::is_better_than(Product b) const {
if (b.price==0) return false;
if (price==0) return true;
return score/price > b.score/b.price;
}

Your turn: Provide meaningful code for Product::print()

Things know (Separate compilation)


The file driver.cpp contains the main program.
Definitions of global variables
Non-member functions
The main routine

Important!!!

Most of the time your compiler


needs to be told where to find
these extra files.

The header file product.h contains the definition of the


class. It might also contain some other useful things:

Definition of constants
Declaration of other classes
Definition of member functions
Declaration of non-member functions
Declaration of global variables

Because you will check your


work against the 'official'
compiler, please make sure
you know how to properly
configure it.

The file product.cpp contains the implementation of


the member functions.

Things (three file layout)


Summarizing, place
the main routine and its non-member functions in the
main source, say hw1.cpp
the class declarations in class.h
the class member function definitions in class.cpp
hw1.cpp
#include "Class.h"
void fun(){
. . .
}
int main(){
. . .
}

class.h
#ifndef CLASS_H
#define CLASS_H
class Class{
. . .
};
#endif

class.cpp
#include "Class.h"
Class::Class(){
. . .
}
void Class::fun(){
. . .
}

Note that both hw1.cpp and class.cpp include the header file
class.h

Things (arrays)
An array is a list values of the same type.
The general form of an array declaration is:
type arrayName[size];

Example:
An array of 5 doubles is declared:
double list[5];

Without [5] it would be just one double.

Any type is OK, even classes.


double listOfNumbers[17];
char spanishAlphabet[27]; // 26 letters + ''
Card spanishDeck[40]; // A deck with 40 cards

Things (arrays cont)


Initialize an array with:
type name[size]={value_1, value_2,..., value_size};

or use a loop.
Elements are accessed by index:
arrayName[index]

Indices start at 0 and the last index is size-1.


Examples:
The code
int someNumbers[]={2, -3, 5, -7, 11, -13, 17, -19};
cout << someNumbers[5] << endl;

displays -13, and


the index of the last element is 7.

Things (arrays in functions)


In a function declaration, to denote that a parameter is an
array use brackets [].
Remember to pass the size of the array as well
unless the size is available as a global constant.
void aFunction(double v[], int size){ . . .

When the function is called, just give the name of the


array (without the brackets)
double myArray[123];
aFunction( myArray , 123 );

They are always passed by reference even without &


Changes are always recorded. Be careful!
Arrays 'cannot' be a return type (wellthey kinda can!?)

Things (2D arrays)


Often times, data is represented in
two dimensions.
E.g: spreadsheet, matrix, table, or
even images.

To declare a 2D array, create and array of arrays


type matrixName[numOfRows][numOfColumns];

To reserve space for the table above:


int magicSquare[3][3];

Actually, just the number of


columns is required. Why???

To access elements indicate the row and the column.


cout << magicSquare[2][1]; // Displays 9

To pass it to a function, specify the rows and columns.


void myFunction( int matrix[rows][cols] ){ . . .

Things (vectors)
Similar to arrays but slightly 'better'.
The library <vector> is needed.

Syntax:
vector<dataType> variableName(size);

size

is a nonnegative integer, it defaults to 0 if omitted.

Any data type can be used. Even classes


vector<string> listOfWords(2015);
vector<BikeFrame> sevenElevenTeamBikes(9);

Vectors can use helpers (member functions). E.g:


int i = sevenElevenTeamBikes.size(); // i = 9

Elements are accessed with [], just like arrays.

Things (vectors in functions)


To pass a vector to a function use
returnType functionName(vector<type> vectorName){

A vector can also be a return type.


E.g: Extract the int sub-vector between positions s and f
of a given vector.
s
-1

Remark:
Vectors can be passed by reference!

f
2

-4

-4

vector<int> extract(vector<int> & v, int s, int f){


vector<int> sub( f - s + 1 );
for ( int i=s ; i<=f; i++ )
sub[i-s] = v[i];
return sub;
}

Things (vector member functions)


Class: vector<data_t>
data_t could be int, double, string, Card, etc.
Member function

Description

vector(int n)

Constructs a vector with n elements.

int size()

Returns current size of vector

void push_back(data_t d)

inserts d at the back of the vector

void pop_back()

Removes last element of the vector.

void resize(int n)

Resizes vector to size n.


If n is less than the old size, elements at
the back are deleted.

Exercises
Write snippets of code that:
Reads the contents of a file into a vector.
Erase an element from a vector (without using the
member function erase(int position).
Inserts an element at the beginning of a vector.
Merges two ordered vectors into another ordered vector.
Use your favorite data type.
Mine is int (in case you were wondering!).

Some solutions will be available at CCLE


but you are always encouraged to produce your own
solutions.

Things (pointers)
We can store memory addresses using pointers.
A pointer is denoted by *.
Keep this in mind:
* = "points to"
& = "address of"
int x = 23; // Creates an integer x and sets its value
int* p;
// Creates a pointer to an integer
// p exists but does not point anywhere
p = &x;
p

// Now p store the address of x


x

23

Things (pointers cont)


Pointers can point to any variable or object.
x

int x = 23;
int* p = &x;

double w = 3.14;
double* q = &w;

3.14
q

Card card1;
Card* r = &card1;
string str = "Hi Manolo!"
string* s = &str;
s

23

card1
r

rank=1
suit=clubs
str

Hi Manolo!

Things (ptrs, address vs value)


Dealing with pointers gets tricky because:
they know where a variable lives (memory address), and
they also have keys to the house (can modify contents).

One has to be careful!


int x = 32;
int* p = &x;
cout << &x << endl;

// displays address of x

cout << p << endl;

// displays address of x

cout << x << endl;

// displays value of x

cout << *p << endl;

// displays value of x

Use *p to access the value of the variable.


This is called dereferencing.

Things (ptrs, summary)


A pointer stores the address (&) of a memory block.
string name = "Manolo";
myPtr = &name;
// points to start of the string

Dereference to obtain/change values.


cout << *myPtr;
*myPtr = "Joaquin";

// displays "Manolo"
// changes string to "Joaquin"

Free up memory with delete.


The pointer survives. Point it to NULL right after.
delete myPtr;
myPtr = NULL;

// deallocates the string block

Allocate memory with new.


string* newPtr = new string; // empty string block
*newPtr = "Maria";
// string stores "Maria"

Things (ptrs in functions)


Just like other variables, pointers can be passed by value
or by reference.
void my_function (int* p, int* &q) { . . .

When a pointer is passed by value (no &) changes to the


address are lost when the function exits
however it could still change the value it is pointing to.
int main(){
int* p = new int;
*p = 42;
funAgain(p);
cout << *p;
// displays 33
return 0;
}

void funAgain(int* p){


*p = 33;
p = 0x7fffff0a3510;
return;
}

Things (ptrs and member functions)


When a pointer points to a class like Card, we can
access its member functions through the pointer.
Card card1;
Card* p = &card1;
p.get_suit();

// ERROR: p is not a Card

*p.get_suit();

// ERROR: p still not a Card,


// . has precedence over *

(*p).get_suit(); // WORKS! gets suit of the


// card p points to

This combination is so common that there is a special


operator -> that is used to access the members of a class
with a pointer.
p->get_suit();

// OK: gets the suit of card1

You might also like