ECE244-LECTURE 1

Course is about

  • C++ language
  • Data structures
  • Algorithm Complexity

Object oriented programming:

Represents concepts and objects that have data fields and procedures

C vs C++

C++ is a superset of C, they have shared features but C++ has more features. The features includes object oriented programming.

Example: Write a computer program that opens a bank account being able to

  • Assign an account number
  • Deposits $100

Method 1 / Method 2 / Method 3
  1. Define variables
  2. Set variables using functions
/
  1. Define a struct with variables
  2. Create a struct
  3. Change struct variables using functions
/
  1. Define a class with instance variables and methods
  2. Create an instance of that class
  3. Initialize the object’s variables using its methods

class accountclass {
private:
int accnum// 4 Bytes !!!!! IMPORTANT
float bal;
public:
int gotaccnum(void);
float deposit(void);
}

Definitions:

  • Class
  • A user-defined type; similar to struct
  • May include data and function
  • Object
  • Is an instance of class type
  • Is a variable whose type is class hence allowing access to members/data (function)
  • Restricting access
  • Public
  • Private
  • Protected
  • Members are only accessible by the class members and the members of a derive class
  • Algorithm
  • A sequence of precise instructions that leads to a solution for a task

ECE244-Lecture 2

Preprocessor directive

  • Lines beginning with # indicate complier’s processor
  • #include means what follows is a filename: find that file and insert its content  <iostream>
  • include definitions of some symbols used later in the code
  • Example: #define HST 0.13

using namespace std;

  • indicates name used in the program (e.g. cin/cout)

Types / Bytes
Int / 4
Float / 4
Double / 8
Long double / 12
Char / 1
Bool / 1

type bool

  • Allow declaration of Booleans(TRUE/FALSE)
  • E.g. bool a = true;

cin/cout

  • Are part of std namespace
  • Are not functions

cin

  • Reads from standard input(keyboard)
  • Stops at whitespace(blank, space, tab, newline)

cout

  • Writes to standard output(display)
  • Is buffered
  • Automatically decides output format

CPU BUFFER DISPLAY

e.g. double x=2;
cout < x;
double y = 3.1;
cout < y;

Insertion operator ( < or > )

  • Essentially pipes(shifts)
  • Data in/out

endl(end of line)

  • Is called stream manipulator
  • Moves custom to a new line
  • Flushes the buffer

ECE244-Lecture 3

Execution of an algorithm

1)Write a program and save as name.cpp

2)Compile prog to generate machine code(0/1)

3)Run executable prog

name.cpp:

  • Editor->preprocessor->compiler->assembly->machine code
  • Editor(vim/emacs)->compiler->machine code

Compile: Run on a terminal

g++ name.cpp //Creates the object file that is executable code a.out
g++ Name.cpp –o Name
man g++
get –g –Wall Name.cpp –o Name

Functions: 3 parts

0/many input  Function name (Body of function) 0/as many
declare(Do it before main) / funcName(type var1, type var2, ..);
define / Type funcName(type var1, type var2, ..)
{
//Body
}
!!!!! IMPORTANT: Type is called Header
#include <iostream>
int fact(int); //Declaration
int main () {
int num;
cout < “Please enter positive int”
cin > num;
while (num<0) {
cout< “Posiitve please””;
cin > num;
cout < num < “!=” <facrnum < endl;
}
return 0;
}
int fact(int n)//Defining
{
int res = 1;
while ( n > 0 ) {
res *-n;
--n;
}
} / Int fact(int &);
Int fact(int &n);

Call by reference: is when the address of the variable is used

!!!!! IMPORTANT:

  • Symbol & is placed next to the variable name in the argument of declaration and header but not function call.
  • In the function definition, variable is treated as a regular one. Any changes made to this variable automatically change the value of variable in caller.

Pass by value / Pass by reference
  • Provides function with its own copy
+Guarantees function cannot change original caller’s copy
-Inefficient: since parameters need to be copied every time /
  • Function cannot copy without 1st making its own
+efficient: no copying
+can have many return values

ECE244 Lecture 4

Recall:

//Factorial: call by value
#include <iostream>
using namespace std;
int fact(int);
int fact(int n) {
int res = 1;
while (n > 0) {
res *= num;
num--;
}
return res;
}
int main() {
int num;
cout < “Enter integer:”;
cin > num;
cout < num < “!=” < fact(num) < endl;
return 0;
}
//Factorial: call by reference
#include <iostream>
using namespace std;
void fact(int &);
void fact(int &n) {
int res = 1;
while (n > 0) {
res *= num;
num--;
}
}
int main() {
int num;
cout < “Enter integer:”;
cin > num;
int tempnum = num !!!!!IMPORTANT: Because num is changed
fact(num);
cout < tempnum < “!=” < num < endl;
return 0;
}

ECE 244-Lecture 5

Modularizing: point is to make multiple .cpp/.c files and separate functionality in each file for clean looking code.

!!!!!IMPORTANT: main.c/main.cpp file should have #include of other files

  • Allows chopping a program into smaller chunks of code called functions
  • Effectiveness of programming can further be improved if code is split into multiple files
  • Each file is compiled separately and then in a final time to link them such that a single executable file is obtained

Steps

  1. Place definitions of variables, declaration of functions, preprocessor directives in a (header) file called interface file
  2. Place definitions of functions in another file(s) called implementation file
  3. Place main() in a file called application file

Certain implementation files (A) need to include other implementation files (B) to use certain functionality. A problem occurs when a third file includes both files(A & B), thereby having redundant includes. For this, we use #ifndef

Syntax:

#ifndef DEF_H //If def.h is not defined
#def DEF_H
//Lines of code
#ENDIF

Example: header file

called def.h
#ifndef DEF_H
#define DEF_H
void point_hello(void);
int fact(int)
#end if
main.cpp
#include <iostream>;
using namespac std;
#include “def.h”
int main()
{
print_hello();
cout < “Please enter integer:”
int num;
cin > num;
cout < fact(num);
return 0;
}
func.cpp
int fact(int n) {
int res = 1;
while (n > 0) {
res *= num;
num--;
}
return res;
}

Build process

  1. Preprocessor includes interface files
  2. Compiler builds object files
  3. Linker takes object files and builds executable

def.h

[main.cpp]  [preprocessor]  [complier]  main.o  [linker]
[func.app]  [preprocessor]  [complier]  func.o  [linker]
[linker]machine code

compile

g++ main.cpp func.cpp –o hello

makefiles (unix ONLY)

  • is a file that contains instructions in how to compile a program files and build executable

Format:

target : dependency1 … dependency1
[tab][tab] commands
# This is a comment
# call and save this file as “makefile”
all : hello
hello : main.o func.o
g++ main.o func.o –o hello
main.o : main.cpp def.h
g++ -c main.cpp //Creates an object file
func.o : func.c
g++ -c func.cpp
clean :
rm –f main.o func.o hello //-f is force
to run, type
make
to clean, type
make clean

ECE244-LECTURE 6

stream

  • A transfer of information in the form of a sequence of bits
  • input <istream> : cin
  • output <ostream> : cout, cerr

[IOS]
[istream] / [ostream]
[istring]
[stream] / [ifstream] / [iostream] / [ofstream] / [ostring]
[stream]
[fstream] / [string stream]

bool bad()

-returns true if fatal error occurred with current stream

bool fail()

-returns true if an error occurred with current stream, otherwise, false

bool good()

-return true if no error occurred with stream

Bool eof()

-return true if EOF occurs

ex) consider what would be displayed?

int a;
float b;
cin > a;
cin > b;
cout < a < endl; //2
cout < b < endl; //0.3
//input 2.3

ex)

int a;
cin > a;
cout < a < endl; //2
//Input: u Output: old value of a
//Input: 22 Output: 22
//Input: x Output: 22
//Input: 0.8 Output: 0
#include <iostream>
using namespace std;
int main () {
int n;
while (true) {
cin > n
if (cin.eof()) {
break;
}
if (cin.fail()) {
cout < “Invalid input” < endl;
cin.clear();
cin.ignore(1000, ‘\n’);
}
else {
cout < n < endl;
}
}
return 0;
}
CTRL+Z/F6 //Suspends process on Unix, closes files on netbeans
//Input: 8 Display: 8
//Input: .8 Display: Invalid Input
//Input: 7 Display: 7
//Input: 0.8 Display: 0
//Display: Invalid input
int n;
while (cin > n) {
cout < n < endl;
}
//Input: 4 Display: 4
//Input: 3 Display: 3
//Input: 0 Display: 0
//Input: u Display: loop terminates

I/O Formatting

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double n = 123.456;
cout < n < endl; //123.456
cout.setf(ios::fixed); //Fixed-point notation
cout < n < endl; //123.456000
cout.unsetf(ios::fixed); //Unsets
cout < n < endl; //123.456
cout.setf(ios::scientific); //Scientific-point notation
//overriding if fixed-point notation has been made
cout < n < endl; //1.234560e+02
cout.unsetf(ios::scientific); //Unsets
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout < n < endl; //123.46, rounding 456 to 46
cout.setf(ios::right);
cout.width(ios::10); //Good for only ONE count < operation
cout < n < endl; //[][][][][1][2][3][.][4][6]
cout < n < endl; //[1][2][3][.][4][6]
cout.fill(‘*’);
cout < setw(10) < n < endl;
//[*][*][*][*][1][2][3][.][4][6]
return 0;
}
int n;
while (cin > n) {
cout < “Hex:” < hex < n < endl;
cout < “Oct:” < oct < n < endl;
cout < “Dec:” < dec < n < endl;
}
Input: 20 Output: Hex:14\nOct:24\nDec:20\n

ECE244-Lecture 7

Pointers

#include <iostream>
using namespace std;
int main() {
int num, var, num;
cin > num;
cin > var;
sum = num + var;
cout < sum < endl;
return 0;
}

int *p;
p = &num;
*p;

Two methods to access memory locations for data

  1. Use name of variable, e.g. num
  2. Use address of the location, e.g. 1000

Address operator &

  • Is used to get the address of a variable
  • &num = 1000
  • to declare:
  • pick a name
  • put an * (called dereferencing operator)
  • Before pointer name e.g.: *ptr, *pf
  • Indicate type, e.g.
  • int *ptr;
  • char *pf;
  • To get a pointer to a point to a variable, just assign the address of variable to pointer
  • ptr = &num;
  • To access data in the memory location whose address is stored in pointer use *
  • e.g. *ptr

#include <iostream>
using namespace std;
int main()
{
int *ptr, num = 55;
ptr = &num;
cout < num < endl;
cin > *ptr; //Put 77
cout < num < endl; //77 now
return 0;
}

New operator (equivalent to malloc)

  • create a variable of specified type dynamically
  • returns the address of the variable
  • e.g.

int *ptr;
ptr = new int;

Delete operator (equivalent to free)

  • delete, a dynamic variable and allows the memory space to be reused
  • e.g. delete ptr;
  • after delete operator is complete
  • The value in ptr is undefined.

#include <iostream>
Using namespace std;
int main() {
int *p1, *p2;
p1 = new int;
*p1 = 42;
p2 = p1; //p2 also points to 42
cout < *p1 < endl; //Prints 42
cout < *p2 < endl; //Prints 42
*p2 = 53;
cout < *p1 < endl; //Prints 53
cout < *p2 < endl; //Prints 53
p1 = new int;
*p1 = 88;
cout < *p1 < endl;
cout < *p2 < endl;
return 0;
}

Mid 2009

Use cin and cout and write code to read a number if number is an integer display “integer”
If number is Real display “Real”
#include <iostream>
using namespace std;
int main() {
int input;
cin > input;
if (input % 1 == 0){
cout < “Integer” < endl;
}
else {
cout < “Display”;
}
return 0;
}

ECE244-Lecture 8

void exit(int exit_code);

  • Resides in <cstdlib>
  • Causes normal program termination
  • Several clean ups
  • Destructors of objects are called
  • Temp files are removed
  • Closes open files
  • exit_code is used by OS
  • exit(0);
  • exit(1);

exit_code / Meaning
exit_success(0) / Successful
exit_failure(1) / Error occurred

FILE I/O (Chapter 6.1) (6.2 output formatting) (6.3)

  • To read from/write to files

#include <fstream>
using namespace stdl
  • Declare input/output stream variable

ifstream in; //Only read
ofstream out; //Write only
fstream inout; //Both
Default
ifstream / ios:in
ofstream / ios:out
  • Open the file and connect the file to stream by using member function open

in.open(“input.txt”);
out.open(“output.dat”);
if (in.fail()) {
cerr < “Input file opening failed.\n”;
exit(1);
}
  • Use input/output streams to read/write to the file

in > var; //In refers to input.txt
out < “Hello”; //Out refers to output.dat
  • Use

stream_var.close();
in.close();
out.close();

Ex)

#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in;
ofstream out;
in.open(“input.txt”);
//in points to the 1st thing in input.txt
out.open(“output.txt”);
//out points to the 1st thing in output.txt
int num;
in > num; //Reads 1 from input.txt
out < “Hello\t” < num < endl; //Writes “Hello\t1” to output.txt
in.close();
out.close();
return 0;
}
//Read numbers find average
int main() {
ifstream in;
ofstream out;
in.open(“input”);
out.open(“output”);
int cnt(0); //Same as int count = 0;
double num, ave, sum(0);
while (in > num) { //while (in.eof()) //in
sum += num;
count++;
}
ave = sum/cnt;
out < “\t\t ave = ” < ave < endl;
in.close();
out.close();
return 0;
}
#include <iostream>
#include <fstream>
#include <cstdlib> //Allows usage of exit();
using namespace std;
int main () {
ofstream out();
ifstream in(“input.txt”);
if (in.is_open()) {
int cnt(0);
double num, ave, sum = 0;
while (in > num) {
sum += num;
++cnt;
}
ave = sum / cnt;
out.open(“output.txt”, ios::out); //Only writing mode
out < ave < endl;
out.close();
}
else {
cerr < “File did not open”;
exit(1);
}
in.close();
return 0;
}

ECE244-Lecture 9

ios::app

  • All output operations happen at the end of the file by appending to its existing contents

stream_var.open(“input”, ios::app);
string filename;
cout < “Please enter file name:”
cin > filename;

Standard input

  • Users often enters invalid input inputs
  • Programmer is required to check for validity of input and prompt user for correct format

Stringstream

  • Is a class defined in header file
  • #include <sstream>
  • Allows a String-Base object to be treated as a stream
  • Can read from/write to string using formatting facilities provided in stream

Lab #2

  • Read inputs with different types/number of inputs
  • Display message

> insertR R0 14.0 1 2
Inserted: resistor R0 14.00 0hms 1 -> 2//Two digits
> modifyR R0 100 1 2
> deleteR R0
> hamid
Error: invalid input
#define INSERT_COUNT 5;
getline(cin, line);
int main () {
cout < “success;” < parser() < endl;
return 0
}
int parser(void) {
cout < “> ”;
string line, command;
getline(cin, line);
// Line = “insertR R0 14.0 1 2\0”, excluding the \n at the end
while (!cin.eof()) {
stringstream lineStream(line);
lineStream > command; //cin > command;
count = word_per_line(line);
if (command == “insertR”) {
if (count > INSERT_COUNT) {
cout < “Error: too many agruments” < endl;
}
else if (count < INSERT_COUNT) {
cout < “Error: too few agruments” < endl;
}
else {
string rname; double res; int node1, node2;
lineStream > rname > res > node1 > node2;
if (res < 0) {
cout < “Error: negative resistance” < endl;
}
else if (node1 == node2) {
cout < “Error: both terminals of resistor connect to node” < node 1 < end;
}
else {
cout < “Insert: resistor” < rname;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout < res < “ohms” < node1 < node2 < “->” > node2 > endl;
}
}
}
else if (command == “ModifyR”) {
//Modify R
}
else if (command == “deleteR”) {
//Delete R
}
else {
cout < “Error: invalid input” < endl;
}
cout < “> “;
getline(cin, line);
}
return 1;
}

ECE244-Lecture 10

structure

  • Allows defining a collection of different types

syntax(defining):

struct name {
type var1;
type var2;
}
struct student {
int num;
double GPA;
char gender;
}

Declaration:

student x;
student hamid; joe;

Accessing members of structure

//dot operator (.)
x.number = 123;
x.GPA = 0;
x.gender = ‘M’;
//Arrow operator (->)
  • is used by a pointer variable
  • declare an instance of structure
  • declare a pointer variable of type structure
  • copy address of structure instance into Pointer
student wen;
student *wenptr;
wenptr = &wen;
wenptr->num=345;
wenptr->GPA=4;
wenptr->gender=‘f’;
(*wenptr).GPA=‘0’; //Changes gpa to 4;

Node

  • is a structure that has both data member and a pointer to the same structure

struct node {
int v;
char c;
node *next; //name of a function can work too
}

Linked list:

  • is a collection of nodes
  • Allows that nodes to be spread over different memory locations

function to insert node at the head;

struct node {int id, node *next};
void head_insert(node *head, int id) {
node *temp;
temp = new node;
temp->id = id;
temp->next = head;
head = temp;
}

Function to add node after given node address

void insert(node *after, int id) {
node *temp;
temp = new node;
temp->id = id;
temp->next = after->next;
after->next = temp;
}

Double-linked list

  • Provides two links to the previous and next nodes
  • Allows traversing in two directions

Deleting a node in the middle of a doubly linked list

struct node {
int id;
node *prev;
node *next;
}
n->prev->next = n->next;
n->next->prev = n->prev;
delete n;
n = NULL;

Lecture 11

#include <iostream>
using namespace std;
struct date {int day, month, year;};
void get_data(date&);
void print_data(date&);
int main {
date myday;
get_data(myday);
cout < “This prog was written on:”;
print_data(myday)
return 0;
}
void get_data(date &d) {
cout < “Please enter day:”;
cin > d.day;
cout < “Please enter month:”;
cin > d.month;
cout < “Please enter year:”;
cin > d.year;
}
void print_data(date &d) {
cout < d.day < “/” < d.month < “/” < d.year < endl;
}
#include <iostream>
using namespace std;
class date { //class header
//class body start
private:
int day, month, year;
public:
void get_data(); // {//Declare function here};
void print_data();
//class body end
}
int main() {
date myday;
myday.get_data();
cout < “This program was written on:”
myday.print_data();
return 0;
}
void date::get_data() {
cout < “Please enter day:”;
cin > day;
cout < “Please enter month:”;
cin > month;
cout < “Please enter year:”;
cin > year;
}
void date::print_data() {
cout < day < “/” < month < “/” < year < endl;
}

Class

  • Is a user defined type, similar to structure
  • May include two kinds
  • Data members
  • Function members

Object

  • Is an instance of class type
  • Is a variable whose type is class
  • Syntax:
  • class_name object_name
  • Three keywords
  • Public
  • Private
  • Protected
  • Followed by colon :

Public:

  • Can be accessed anywhere in program that has an object of that class

Private

  • Members can be accessed only by class member

Protected

  • Members are only accessible by the class members and members of a derived class

Data Hiding:

  • Making a class data private prevents data to be accessed from outside the class. This is termed as data hiding
  • Member functions are used to access the data, hence controlling the access to data
  • Default is private, so if you don’t put public/protected, it’s private automatically

Encapsulation