Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Wednesday, September 9, 2020

ECCS Lecture Notes


https://www.icloud.com/pages/0seAKjoV41YP1tC8hbec4AqIg#EECS_Lecture_Notes

Lecture 2
2.1 Pseudocode and Programming Languages:

-Pseudocode is a compiled number of steps that describes a command

-C++ and code describes the steps in computer language in order for the computer to
compute commands.

2.2 Parts of C++ Program

-A statement—Has a semicolon and is the individual instructions of a program.

-Ex: cuot<<y;

-Expression— An expression does a function that is evaluated and returns a value

-Ex: 2+3

-Variable Declaration—De nes a variable in the code

-Ex: int x = 2; (also a statement)

2.3 Tracing Through Programs

-Ex:

Int main () { Variables: Console:

Int x = 3; x = 3

Int y = x; y = 3 33

x = 3;

cout << x;

cout << y;

Return 0;

1
fi
Wednesday, September 9, 2020

2.4 Compile Errors

-Like a grammar error where the computer doesn’t understand what is being said

-Ex: int x = int y + 1 (can’t introduce y on this side)

-A bug is when the computer is told what to do but does the wrong thing

Lecture 3
3.1 Types

- int: Store whole numbers

- Double: Store and rational number

- Bool: Stores true or false

- String: Stores 0+ symbols—letters and numbers

- Char: Stores a single symbol

3.2 Operators

- Operators fo math with numbers and variables

- Integer division:

- Division of integers reports a integer

- Division with a double reports a double

- The modulo operator (%) does reports the variable

- 7%3 = 1

3.3 Tracing Through Programs

- Nothing to note

3.4 Implicit and Explicit Type Conversion

More Values —————————————————————————>Less Values

double int char bool

<—————————————————————— Implicit Conversion (automatic)

Explicit Conversion ————————————————————————-> (cast)

2
Wednesday, September 9, 2020

-Implicit Conversions

-int + double = double

-int + int = int

-double + double = double

-Explicit Conversion

-static_cast<int>(x);

3.5 Rounding Functions

-Must include #include <cmath>;

-Rounding Functions:

- round ( ) - rounds to the nearest integer

- oor ( ) - rounds down to nearest integer

- ceil ( ) - rounds up to nearest integer

-Ex: d=3.7

- round (d) = 4

- oor (d) = 3

- Ceil (d) = 4

Lecture 4
4.1 Functions

- Splits code into sections, and each section has a task

- Makes big programs into many little programs

- Makes the code easier to write and reduces code duplication

Input ---------> function ----------> output

3
fl
fl
Wednesday, September 9, 2020
Parts of a function:

Example: square function

_____________ nameOfFunction(_____________________){

(output type) (input parameters)

return _____________;

(output value)

Example: Filled out function

int doThatThing( int a, double z, string s){

//function goes here

Function Header: Describes the interface for the function

-what the function called (doThatThing)

-what the inputs are called (int a, double z, string s)

-what the outputs are (int)

4.2 Calling a Function

Function call: Jumps to a function from main or another function

Example: Trace through a program "square"

double square(double d) {

return d*d;

int main() {

double s; Declares a new variable s

4
Wednesday, September 9, 2020
double z = 3.0; Declares a new variable z = 3.0

s = square (z); function call (square), z = 3.0, the value of z become d, runs

cout << s; square, and then outputs 9.0 into s.

return 0;

4.3 Common Mistakes

Input Rules:

- Can have 0 or more outputs

- Types and identi ers in function header

- Input values are passed in by function caller

Output Rules:

-Can only return one or zero things

-Return value must match return type stated in header

Function calls:

-Provide input values to functions

- Store, print , or use return value

Lecture 5
5.1 Scope

-Scope: where something can be used

Example: Example:

int main () { int x = 3;

int x = 3; y = x;

int y; int y; <=== Y introduced too late

y = x; return 0;

return 0; }

} Doesn't Run

Runs

5
fi
Wednesday, September 9, 2020
5.2 Pass by Value

-Pass by Value: Passing data to a function makes a copy

Example:

Void addOne(int x) {

x = x + 1

cout << x;

int main () {

int x = 3;

addOne(x);

cout << x;

5.3 Cin Algorithms

Example:

int x;

cin >> x;

(user types in the value of x)

6
Wednesday, September 9, 2020
5.4 Cin Fail State, getline(), other inputs

cin fail state:

input eecs

input x; <---- This is the fail state, because the letters aren't integers, so all other cins
do nothing

cin >>x;

string s;

cin >> s;

- What if we want to read a string with whitespace

use getlin()

Example:

input "Hello world"

getline(cin, s);

Lecture 6
6.1 RME Comments

-RME stands for requires, modi es and e ects

-Requires: What are the constraints on the function

-Modi es: What changes in the function

-E ects: What the function does

-Example:

/* requires: count > 0

modi es: Nothing

e ects: Returns average of count and the elements that end up in sum

7
ff
fi
ff
fi
fi
ff
Wednesday, September 9, 2020
double average(double sum, double count) {

return sum/count;

6.2 If/ else if

conditional: if/else,, ask a yes/no question and then act upon it

-example

if (windChill < 0) {

cout << "brrr"

} else if (windChill < 32) {

cout << "comfy";

} else {

cout << "toasty";

6.4 Boolean Expressions

-math with true and false

-compare numbers

-combine true and false

-compare numbers

>, < > <= , >=, ==, !=

-combine true and false

|| - or- one or both are true

&& - and - both are true

! - not - not true

8
Wednesday, September 9, 2020
6.5 Completments

complements- complements are opposites

Lecture 7
7.1 While Loops

Loop- A block of code that repeats

Example:

int i = 0 variables

while (i < 3) { 0123

cout << "hi"

i = i + 1 console

} hihihibye

cout << "bye!"

-count control loop: executes a certain number of times and made up of three parts

example:

int i = 0 <=== 1) counter variable

while (i < 3) { <=== 2) comparison of counter variable

cout << "hi"

i = i + 1

cout << "bye!" <=== 3) update counter

9
Wednesday, September 9, 2020
7.2 Event Controlled Loops (Cin Loops)

-Event loop also known as cin loops use cin in a while loop

- Evaluates to true when something successfully reads into x and false when it fails to
read into x

Example:

int main() { Variable

int x; 0123D

while (cin >>x) { Console

cout >> (x+1); 234done

cout << "done" << endl;

return 0;

7.3 Cin Loop with Check

- cin loop with an additional condition

Example;

int main() {

int x;

while (cin >>x && x > 3) {

cout << (x+1);

cout << "done" << endl;

return 0;

10
Wednesday, September 9, 2020
Example:

int main() {

int x;

while (cin >>x && x <5) {

cout << "too small";

cout << "big enough" << endl;

return 0;

7.4 i++, i+=, and Friends

-Compound assignment operators

i = i + 1 i = i - 1

the same as the same as

i +=1 i -=1

i++ i--

++i --i

-Some others

+=, -=, *=, /=, %=

Lecture 8
8.2 For Loops:

- Count controlled loops: Excecute a cetain amount of times.

11
Wednesday, September 9, 2020
Ex:

int i = 0;

for (i = 0; i < 5; i++) {

cout << i;

- Count controlled vs event controlled:

count controlled: event controlled:

-execute a certain number of times -loop until something happens

-better for for loop -better for while loop

8.3 Nested Loops

- nested loops: loops inside loops

Ex:

for (int i = 0; i < 2; i++) {

cout << "i = " << i << "begins" << endl;

for (int j = 0; j < 2; j++) {

cout << "j = " << j << "begins" << endl;

cout << "i = " << i << " nished" << endl;

8.4 Scope with Nested Loops and if Statements

- Scope: where a variable can be used

12
fi
Wednesday, September 9, 2020
- Scope with loops:

Ex: Ex:

for (int i = 0; i < x; i++) { int i;

cout << i << x; for (int i = 0; i < x; i++) {

} cout << i << x;

cout << i << endl; }

cout << i << endl;

DOESN'T WORK!! WORKS!!

- Scope with if Statements:

x y z Yields and error because of scope

int x = 7; -

int y; - -

if (x < 10) { - -

int z = x - 10; - - -

x += 2; - - -

} - - -

y = x + z; - -

Lecture 9
9.1 Expressions with Strings

-Strings: zero or more chars in a row

-string comparison:

- == means the same character to character

- != means not identical character to character

13
Wednesday, September 9, 2020
9.2 String Indexes

Ex:

string s = "Hello";

index of string s:

h e l l o

0 1 2 3 4

-index of s = 4

- The index is the distance from the beginning of a string

9.3 String Functions + Loop and String

- .length(), .size() - gets the char count of string

Ex:

string.s = "hello";

cout << s.size(); -------> 5

- .at()

Ex:

string.s = "hello";

cout << s.at(2); -------> "l"

Ex:

string s = 'sup';

s.at(1) = 'c';

cout << s; -----> suc

-strings and loops

Ex:

string s = 'hello';

for (int i = 0; i < s.size(); i++) {

cout << s.at(1);

14
Wednesday, September 9, 2020

Lecture 10
10.1 Pass by Value and Pass by Reference

-pass by value: makes a copy

-original variable/value and thing in function are seperate

- helpful when variables hold a lot of information (string functions)

Ex:

void f(int x) {

x = 3;

int main() {

int x = 2;

f(x);

cout << x; -----> 2

-pass by reference

- uses an &

-one thing (the original)

-function gets a new name for that thing

-one variable has more than one name

Ex:

void f(int &x) {

x = 3;

int main () {

int x = 2;

f(x);

cout << x; ------> 3

15
Wednesday, September 9, 2020
Ex:

void multiply(int &x) {

x = x * 2;

int main () {

int a = 3;

multiply (a);

cout << a; -------> 6

return 0;

10.2 Tracing with Pass by Reference

10.3 When to use Pass by Reference

Ex: ERROR

void addOne( double &x) {

x = x + 1;

int main() {

addOne(3.1);

double a = 3.1;

addOne(a + 1);

int y = 3;

addOne(y);

return 0;

16
Wednesday, September 9, 2020
Ex: FIXED


void addOne( double &x) {

x = x + 1;

int main() {

double d = 3.1;

addOne(d);

double a = 3.1;

double d2 = a + 1;

addOne (d2);

int y = 3;

addOne(y);

return 0;

Lecture 11
11.1 Source Code (.cpp) and header (.h) les

- Seperates codes in order to organize the functions

- .h declares functions and has RMEs

- .cpp includes .h and implements functions

11.2 Declaring Arrays and Accessing Elements

- With an array, you can store large amounts of variables instead of declaring all the
variables by assigning a number to the variable

- string students[1110] -- declares all 1110 students

- Example:

int main() {

int arr[3]; <---- type int, name arr, 3 spots (starting from 0).

17
fi
Wednesday, September 9, 2020
-Array sizes must be known at compile time

- number

-stored in constant

-Example:

good

-int arr[2];

-const int SIZE = 4;

int arr[SIZE];

not good

-int size;

cin >> size;

int arr[size];

-initializer lists put stu in arrays

-Ex: int arr[4] = {-1,5,0.2};

-Ex; int arr[4] = {-1}; puts 0's in the rest of the spots

- can initialize with blank spots

-Ex: arr[4];

-Arrays can be accessed with indexes

- int b[ ] = {-1, 5, 0, 2};

cout << b[2]; <--- prints 0

11.3 Looping over Arrays

- array loops allow us to access parts of the array

- array loop example

cont int SIZE = 3;

int arr[SIZE] = {1, 2, 3};

for (int i = 0; i < SIZE; i++) {

cout << arr[i];

18
ff
Wednesday, September 9, 2020
-Things you cannot do with arrays

- Cannot cout with arrays

- Cannot += with arrays because they have xed sizes

- Ask how size with .size() or . length()

-Have to track with constants

11.4 Passing Arrays to Functions

-Example:

int lastElement(int arr[ ], int size) {

return arr[size - 1];

int main() {

int arr[3] = {6, -3, 4};

cout << lastElement(arr, 3); <----- Prints out 4

return 0;

-Example:

void f(int arr[ ], int size) {

arr[0] = 4;

int main( ) {

int arr[3] = {8, 2, 1};

f(arr, 3);

cout << arr[0]; <------ Prints 4 (turns 8 into 4)

return 0;

19
fi
Wednesday, September 9, 2020

Lecture 12
12.1 Review Arrays

- Arrays store many values in a single variables

- int arr[3] = {4, 5, 6};

- index 0 1 2

- variable 4 5 6

- Example: What are the bugs?

- int greater10(int arr[ ]) { <----- array does not have size

int count; <------ uninitialized

for (int i = 0; i < arr.size( ); i++) { <---- cannot use .size with arrays

if (arr[i] > 10) {

count ++;

return count;

-Common Errors

- The name of an array refers to the entire data structure

-int score[5] = {30, 40, 50, 60 , 70, 14};

-score holds the memory address of the rst array element

- the variables stored are score[0] score [1] score [2] up to score[5].

-c++ does not check array indices for validity

- If there is int data[5] = {1, 2, 3, 4, 5} and you print data[5], a random


value will be printed

- comparing arrays does not work, but will compile

- arr1 == arr2 will always be false

arr1[i] == arr2[i] in a loop will work

20
fi
Wednesday, September 9, 2020
- Arrays as function parameters

-Your cannot have an array return type

12.2: 2-D Arrays

- 2D arrays

- Regular arrays: 1D like a line of values

-arr[1]

- 2D arrays: like a rectangle of values

- int arr[2][3];

-Initializing 2D arrays

- int arr[4][3] = {

{1, 2, 3},

{1, 2, 3},

{1, 2, 3},

{1, 2, 3}

};

-2D loops and 2D arrays

- Example:

-pattern: outer => rows, inner => columns

int arr[2][3];

for (int row = 0; row < 2; row++) {

for (int col = 0;, col < 3; col ++) {

arr[row][col] = row * col;

- 2D arrays as Parameters\

-arrays are always passed by reference

-Example:

void processArray(int data[50][3], int numRows, int numCols);

21
Wednesday, September 9, 2020

Lecture 13
13.1 Reading from Files: ifstreams

-Streams

- Sends data into and out of a program

-Why use les

- send input and output to other people

-can be larger and also be much faster

- In order to read les you have to use a le stream

- Types of streams

- ifstream: input le stream -- reads a le in

-ofstream: output le stream -- reads a le out

- Reading from les

- The fstream library contains the datatypes

- #include <fstream>

-ofstream: writing to les

-ifstream: reads from les

-Istream syntax

-Example: include input.txt

#include <fstream>

int main( ) {

ifstream n; <----- variable of type ifstream

n.open ("input.txt"); <------ connects to le you want input.txt

int x;

n >> x;

n.close( );

return0;

22
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Wednesday, September 9, 2020
- Four steps for reading from a le

1) declare an ifstream variable. ifstream n;

2) associate the ifstream with a le n.open("input.txt");

3) read from the le n >> x >> y;

4) close the le n.close( );

13.2 Writing to Files: streams

- ofstream syntax

- Example:

#include <fstream>

int main ( ) {

ofstream fout; <--- variable of type ofstream

fout.open("output.txt"); <--- will create a new le if


output.txt does not exist

fout << "Hello";

fout.close( );

return 0;

- Four steps for reading from a le

1) declare an ofstream variable. ofstream fout;

2) associate the ofstream with a le fout.open("input.txt");

3) read from the le fout >> x >> y;

4) close the le fout.close( );

13.3 Stream States

-stream states : there are multiple di erent stream states

-Types:

- .fail( ) -- checks to see if the function didnt work

- .good -- checks to see if the function is good to read more

- .eof -- checks to see if there is nothing more in the le, reached the end

23
fi
fi
fi
fi
fi
fi
ff
fi
fi
fi
fi
fi
fi
fi
fi
Wednesday, September 9, 2020
- .clear( ) -- clears a fail state

- The state gets set AFTER the failure, not before

-clearing states:

- Example: User enters "word"

int x;

cin >> x;

if (cin.fail( )) {

cin.clear( );

string s;

cin >> s;

Lecture 14
14.1 De ning Classes

-What are classes?

- Packages of data and functions that belong together

- Class syntax: declaring

- Example:

class Student {

public: <--- other people can use things in our class

string name; <-- member variables, variables that are part of a class

int umid; <--

}; <--- must end with a semicolon with classes

- Class syntax: using

-Example cont.

int main ( ) {

Student s; <--- student takes the place of the identi er

s.name = "Natalie"; <--- will out natalie inside of the name


member variable of the class

24
fi
fi
Wednesday, September 9, 2020

14.2 Member Functions

- Member functions

- classes are packages of data and functions that belong together

class Student { <== class declaration

public:

string name; <== member functions

int umid; <==

void printName( ); <== member function & declaration

};

void Student::printName( ) { <== current instance is s1

cout << name; <== name comes from current instance of the class
.
(current means variable of class type)

int main ( ) {

Student s1;

s1.name = "Natalie Emcard";

s1.umid = 99999901;

s1.printName( ); <== calls member function

14.3 Constructors

- Constructors

- member function whose job it is to initialize member variables

- almost every class has a constructor

-Constructor syntax

- special member function

- no return type

25
Wednesday, September 9, 2020
-same name as class

- Example:

class Student {

public:

student (string name_in, int umid_in); <== no return type

private:

string name;

int umid;

};

Student::Student(string name_in, int umis_in) { <== Student:: means


belongs to student class

name = name_in;

umid = umis_in;

- Non-default constuctor

-has parameters

- Example:

Student::Student(__________)

- Default contructor

- has no parameters

- creates a blank object- empty string or zero

- Example:

Student::Student( ) {

name = "";

umid = 0;

26
Wednesday, September 9, 2020
-Using Constructors

- Example: Using conductor above

int main ( ) {

Student s1("Natalie Emcard", 99999901); <== Creates an instace of


Student called s1 and
calls constructor

Student s2; <== creates instance called s2 and calls default constructor

Lecture 15
15.1 Header Files

- Copying class instances

-Example:

student s1 = {"Jiaying"};

student s2;

s2 = s1;

- Passing class instance to a function

- Example:

changeName(Student s_in, string newName) {

s_in.name = newName;

s_in.printName( );

int main ( ) {

Student s = {"Dean"};

s.printName( );

changeName(s, "niels");

s.printName( ); <== prints Dean, Niels, Dean

- Header les

- .h les tell c++ what to expect, contain functions declarations and prototypes,
. RMEs, and class de nitions

- .cpp les contain function de nitions, where code goes

27
fi
fi
fi
fi
fi
Wednesday, September 9, 2020

15.2 Member access controls

- Public and private access

- Public: functions outside of the class can access

- Private: Only member functions can access

- Why public or private?

- Helps prevent errors by stopping bad input from getting into a class

- private will give class control over what goes into member variables

- When do you use?

- member variables are almost always private

- member functions:

- public if useful to call them from main( ) or outside functions

- private otherwise

15.3 Getters and Setters

- Getters and Setters

- Functions that let us access member variables

- Example:

setter

- void Student:: setUmid( int umid_in) {

umid = umid_in;

getter

- int getUmid( ) {

return umid;

28
Wednesday, September 9, 2020
15.4 Constructors

-Constructors

- A constructor is a member functions whose job is to initialize member


. variables

-It is what creates the instance of a class

-Almost every class with a private member variable has a constructor

- Constructors are special member function

- no return type

- same name as class

- Example:

class Student {

public:

Student(string name_in, int umid_in);

private:

string name;

int umid;

};

in the .cpp le

Student::Student(string name_in, int umid_in) {

name = name_in;

umid = umid_in;

- Using constructors

- Example:

int main ( ) {

// Creates a student with name "michael Michaud and umid 63873804

Student s1( "Michael Michaud", 63873804);

//Creates a student with name "Emily Britton" and umid 45897856

Student s2( "Emily Britton", 45897856);

29
fi
Wednesday, September 9, 2020
}

Lecture 16
16.1 Overloaded Constructors

- Constructors: A member function whose job it is to initialize memebr variables

-Non default: has parameters

-Default: no parameters

- Overloaded Constructors

- Same function, di erent parameters

- Example:

classStudent {

public:

Student( string name_in, int umid_in);

Student (string name_in);

Student( );

private:

string name;

int umid;

};

int main ( ) {

Student Michael( "Michael", 63873804); <== string, int -- rst one

Student Emily("Emily"); <== string -- second one

Student Deron; <== Default constructor -- third one

- Auto default constructor rule

- every class automatically gets a default constructor that does nothing

- If you write any constructor, then it takes away this default constructor

30
ff
fi
Wednesday, September 9, 2020
16.2 Memebr variables of class type

- Member variables of other class types

- Example:

Class Student {

public:

string name;

int umid;

};

class DormRoom {

public:

Student resident;

string dorm;

int room;

};

int main( ) {

DormRoom dr;

dr.dorm = "South Quad";

dr.resident.name = "emily";

cout << dr.resident.name.length( );

Lecture 17
17.1 Read and Write e Functions

- Classes and I/O

-Design classes to look after themselves

- .read functions read in functions

- .write functions write out functions

17.3 I/O when Member Variables are Classes

31
Wednesday, September 9, 2020

32

You might also like