CSE 240 Ch 2

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Formatted C++ input/output

'using namespace std' for C++ I/O, '#include <iostream>' for C-style I/O in C++, cin >> i (input an integer), cout << "i = " << i (<< endl)

char *p = "send me your password", *q;

*p creates a string constant and pointer *q is also a constant, pointer pointed at constant acts as constnat(slide 5 pointers, arrays, strings is confusing)

long int

+- 2,147,483,647 ; 32 bits

char

-127 to 127 or 0 to 255, 8 bits

signed char

-127 to 127, 8 bits

int

-32,768 to 32,767 ; 16 bits

short int

-32,768 to 32,767 ; 16 bits

pointer notation

->, pointer to structure (in Java the [obj].value is pointer)

byte

0 to 255, 8 bits

unsigned char

0 to 255, 8 bits

unsigned long int

0 to 4,294,967,295 ; 32 bits

unsigned int

0 to 65,535, 16 bits

in-class exercise answers

1) b 2) a 3) a 4) d 5) c (slides on Bb)

when you declare an array, which is valid? 1) const int max = 20; char a[max]; 2) #define max 20 char b[max];

1) does not work in visual studio 2) works in all environments

fantastic four abstract approach

1. Formulate the size-n problem 2. Find the stopping condition and the corresponding return value 3. Formulate the size-m problem (m < n) and find m [often m = n-1] 4. Construct the solution of size-n problem from size-m problem (similar to induction)

double

10 decimal digits of precision, 64 bits

long double

10 decimal digits of precision, 64 bits

decimal

128 bits

String

16 bits each

Merge sort

2 recursive calls,

functions (Components of C/C++)

2 types: built-in (pre-written in libraries) and user defined functions ; may exist outside of class (global, also global variables) ; each program must contain one main() function (outside of any class)

sorting algorithms

2.8 in textbook

2D array of string in C

3D array, each element is is a pointer, 3 levels of for loops to navigate char by char (can use strlen in innermost loop) OR get initial address of each strings and print that point as a string OR increment with pointer of pointer for each string

Assume this is a 32-bit environment, given a declaration: int a[10]; What is the size (in bytes) of the entire array?

40

float

6 decimal digits of precision, 32 bits

Registers

D-flip flops, 32 registers at 32 bits each, 50-200ps(access time)

Main Memory

DRAM, 16GB, 50-70ns, $20-$75/GB

mutually recursive function

F calls G, G calls F ; does not allow declaration before use, Forward declaration puts ex)void bar(void); to show signature, I/O type, don't have to worry about order of functions

Buffer maps

I don't really get it, buffer is a queue structure, \n turns into \0

pointers are

IMPORTANT

Secondary storage

Magnetic Disk, 2TB, 5-20ms, $0.20-$2/GB

in class exercise

Q1: ? Q2: when there is one node only, when list is empty (head and tail point to same node), Q3: the first node, Q4: no, case 3 is not included because you have to set the tail pointer, Q5: C, both their nodes contain two pointers to their own types

Cache

SRAM, 0.5GB, 0.5-2.5ns, $200-$500/GB

Given the C declaration: char s1[4], s2[ ] = "hello"; if a string copy function strcpy(s1, s2) is executed, what will happen?

The result s1 will contain the string "hell", and the following two byte loactions will contain 'o' and '\0'.

Variables and library allegory

Value stored (book), Location (place book stored on bookshelf), address(numbers for where book and shelf are located), name (name of the bookshelf)

endl

\n in C++

tree

a graph without a loop and one path between each pair of nodes, height is number of edges from root, root to farthest leaf

char s1[] = {'a', 'l', 'p', 'h', 'a'}; in memory

a l p h a ; size = 5

char s2[] = "alpha"; in memory

a l p h a \0 ; size = 6

function purpose

abstraction and reuse

Pointers in C/C++

address can be assigned to pointer, address stored in pointer can be modified, & Referencing (get address of variable from its name), * Dereferencing (create a variable name for a given address)

what is a program

algorithm (steps of data manipulation, emphasized by imperative) and data (object of manipulation)

binary tree search

also recursive

pointer memory space

always 4 bytes

pointer size in memory

always 4 bytes

L-value

an expression with a location associated with it, can occur on left or right side of an assignment

r-value

an expression with a value but no location associated with it, can only appear on the right side of an assignment

binary tree

any node can have at most 2 next nodes (child nodes), linked list is a tree, binary tree

midterm

be able too identify recursive steps, write own recursive function, 13 multiple choice, review slides, 20 pts. writing questions, answer questions by code given, write small pieces of code, go to UGTA review session

C++ types

bool (boolean), wchar_t(wide-character, 2 bytes = 16 bits), char, int, float, double, void

Buffer in file system

buffer is an invisible array of bytes or characters, use (C: scanf, getc, putc, fflush) or (C++: cin, cout, cin.get, cin.getline, cin.ignore)

linked list

build node in struct containing pointer to next (ex: struct contact *next), first struct is declared with pointer (ex: *head = NULL;), a graph

passing a structure into a function

call by pointer(*y parameter) creates new address, call by value(y parameter) uses same address

call-by-address vs. call-by-alias

call-by-address(call-by-pointer) has formal parameter hold address as variable, but in call-by-alias(call-by-variable) has formal parameter hold same variable, does not pass in value, but only variable

2D array of chars

can be treated as a 1-D array of strings

fantastic four step 3

challenging step, reduce problem by one iteration, m may be n-1, but by specific application may be something else [ex: factorial(n-1);], do not try to solve problem, assume the return value will be able to solve the problem[ex:n*factorial(n-1);]

%c

char

types in C

char (1 byte=8 bits), int, float, double, void

passing string address using pointer

char *getString(char *str)

truncated initialization

char s2[4] = "alpha" ; -> a l p h ; size = 4

fantastic four step 2

check stopping condition first, then enter recursion, often stopping condition and corresponding value is trivial

unformatted C++

cin.getline() to get input with a space, cin.getline(destination, size, terminationChar); <- enter characters to size or enter terminationChar to end input, always terminates on enter

flush buffer

cin.ignore() or fflush(stdin)

functions

communicate with rest of the code using global/static variables, but more often parameters/return values

constants in C/C++

compiler may substitute values for constant definitions - constant defined as a macro (#define max 20, not modifiable), constant may be a variable that the program cannot modify - has to read memory, so slower, declared as const int i; i = i + 2; will cause a compilation error

linked list functions: search()

create as a struct, create local variable stack, 2 pointers, find target with bigger(first) pointer and return smaller(second) pointer

search in linked list

create new pointer at beginning, and another behind it, compare what is at the 2 pointers. Earliest (2nd) pointer is used for insertion and deletion, as we can not refer back with linked list

linked list insertion to arbitrary position

create pointer to certain node, then do insertion operations fro that node instead of head

data declaration

declaration binds name to location and gives type, scope, and qualifier of the value to the location

free(t);

delete piece of memory assigned by malloc where t is a temporary pointer, not using it leads to memory leak

deleting an entire linked list

delete step-wise with while loop(move temp pointer, then delete head, then set head to temp) or recursively

*

dereferencing, giving name, can be on both sides, (l-value), unary, returns an l-value

pointer extra practice

do some!

memory is byte-addressable

each byte has its own address, address of int, float, and pointer must be multiples of 4

fgets (unformatted C-style)

enter string with spaces (can't use spaces with scanf), formating ex: fgets(variable *destination, size, file type *source), fgets(name, sizeofName, stdin) <- stdin reads keyboard input and stores it in name

Google Big Table

extended binary search tree, B+ tree, keeps sorted data, all records stored in leaves, insert with red-black tree for balance

fantastic four step 1

find n for number of iterations, often use n as parameter [ex: int factorial(int n)], return value will be what we are looking for

sizeof

find number of bytes used

insertion algorithm in binary search tree

first number as root, smaller to left, larger to right; worst case input is sorted and forms linked list O(n), typically unbalanced tree O(n); can restructure tree to be balanced with every insertion Olog(n)

%f, %5.2f

floating point number, have 5 digits and 2 decimal places

formal and actual parameters

formal parameter is local variables in the function, actual parameters are the actual variable/values

C input/output (C-Style)

formatted: printf(); and scanf(); included through #include <stdio.h> (input/output library), scanf("%d", &i) <- '&' means taking address as input (a pointer), not name, printf("i = %d, n = %d\n", i, n) <- in this case want the value of i and n

industry application: amazon.com recommendation list

frequently bought together items are made automatically

imperative paradigm

fully specified and fully controlled manipulation of data step by step, abstraction of store program concept, algorithmic, popular for good performance(efficiency b/c works like the computer) and step by step system(familiar)

when using an array, in a loop a-- will...

go to the previous value of array, regardless of type

modules and packages

group programs to make a library,

full binary tree

has each node with 2 or 0

pointer and unsigned int type

have the same data range (0 to 2^32 -1), both support + and - operations, pointer does not support * and /; C/C++ supports coercion and casting between the 2 types as it makes sense.

%x

hexadecimal number

Delete node at arbitrary position

if node is first(head = head->next;), if node is in middle (b->next = p->next; where pointer p is one node ahead of pointer b);, if node is at end, use search to find pointer to proceeding node(b->next =0;)[this case is unnecessary], in all cases use free(t); to delete piece of memory

*(p++)

increment address first, then access

Arrays in C/C++

individual elements accessed by index, string is array of characters

the name of the array is the initial address of the array

int x = 5, *xptr; int y[10], *yptr; xptr = &x; yptr = y; yptr = &y[0]; 2D array: char ma[4][8]; ptr = &ma[0][0];

Pointer

is a variable, gives an address a name, has data (location address), location(in memory), address (number of memory location), name (name for location, &name refers to address of location)

The imperative programming paradigm is popular and is a part of object-oriented computing paradigm, because it ____ (Select all answers that apply).

is based on computer organization and thus is efficient to execute on hardware. AND matches the culture of doing things by following the step-wise instructions.

int *j = 0 means...

j is set to 0

balanced binary tree

leaf nodes can only differ by one level, fast search (more than other binary trees) O(logn)

postorder traversal

left-right-root

Inorder traversal

left-root-right

struct (structure)

like a class in java, but without methods; struct person { char name[30]; long phone; char id[12]; } p;

(int*) malloc (40);

like keyword new(); in Java, stands for memory allocation, in this case 40 consecutive bytes cast for storing ints, new int[40]; in C++

linked list vs array

linked list has structs without consecutive memory connected by a pointer while array is all consecutive, linked list gets memory as needed, array gets memory all at once, array memory can come from static,stack,or heap, while linked list is always heap(malloc)

shortest and simplest program

main () {}

main()

main can take arguments and specify output, ex: double main (int argc, char a) { ...; return...}

make own library

make a c file (wind 32 project DLL) myLib.c, put global variables and functions in, make header file myLib.h to hold forward declarations, in a separate file just #include "myLib.h"

recursion is important for 310

make sure you understand

search speed is _____ important than insertion speed

more

graph

more than one next node allowed

applying fantastic four

multiple examples in slides, insertion sort

function/procedure/subroutine

named block of code the must be explicitly called

\0

null terminator (null character), automatically added to the end of a string

binary search tree

number in each node, ordered

recursion

only deal with 1st and last step (all middle is handled by recursion), only necessary if wee need to repeat the same operations a number of times

char *p

p ->

parameter passing

pass actual parameters to formal parameters, most use call-by-value: formal parameter is initialized to value of actual parameter (no side-effects, less flexible/powerful/efficient), call-by-address: formal parameter is a pointer to actual parameter, call-by-alias: formal parameter is alias of actual parameter, refer to same memory(only in C++), also global variable/static variable and call-by-name

copy array size 7 to size 6

places extra in memory somewhere, does not give an error (semantic)

to access members of linked list structure

pointer = malloc(sizeOf(struct contact)); [to get proper amount of memory to hold structure with pointer, struct obj. has no name] scanf("%s", p->name); scanf("%d", &p->phone); scanf("%s", (*p).email);

pointer to manipulate 2D array

pointer has its own memory address and value, store memory address of first element in pointer value (*p is value in address), need to know ASCII code of values (ex: '\0' is 0)

use pointer to navigate array

pointer is faster than using numbers with initial element of array + change; more consecutively, not from beginning everytime

HW 7/8: print forward/backward

print first in recursive call, print backward put print second at end of recursive call

char q[ ] = "morning"

q= "morning"

&

referencing memory, on right side only(r-value), returns r-value, unary operator

Data in imperative paradigm

represented by states (variables and values), type, location (where data stored in memory), address (integer associated with location), reference/pointer (name associated with the variable holding the address), name, value , scope (lifetime) and visibility

preorder traversal

root-left-right

char *s = "hello"

s -> "hello"

signed int

same as int, 16 bits

signed long int

same as long int, 32 bits

signed short int

same as short int, 16 bits

unsigned short int

same as unsigned int, 16 bits

wchar_t

same as unsigned int, 16 bits

scope rule

scope of a variable starts at declaration point and extends to the end of current braces, need to be declared before use

C/C++ modifiers

signed, unsigned, short, long

%d

specify integer type

%s

string

printf("%s", array) will print

string of array, excluding the null terminator

array of structures (slide 63)

struct contact { char name[30]; int phone; char email[30]; } struct contact contactbook[max]; int tail = 0; //methods void branching(char c); int insertion(); int search(); int delete();

cin.ignore()

switch from cin>> to cin.get or cin.getline, cin>> leaves delimiter inn buffer, can flush a certain number of characters (cin.ignore(int n)) or number of characters or stop at a certain char (cin.ignore(int n, char term))

t = (int*) malloc (40); t[0] = 5;

t can be treated as array by memory allocation

What is NOT the purpose (functionality) of the forward declaration (prototype)?

to allow a function to return different types of values

pointer vs memory incrementation

to increment pointer use p++, to increment what is in pointer current address use *p = *p + 1

C/C++ allows direct access to memory address

true, can still use name if wanted & available

bool

true/false, 1,8 bits

type construction and enum

typedef enum {false, true} boolean; boolean x = false;

typedef

typedef typename newname; makes a new name that becomes a synonym for the type of typename ex) typedef char FlagType; FlagType x = '10';

switching from unformatted to formatted

unformatted input leaves a '\n' in the input buffer and needs to be flushed by fflush()/getchar()/cin.ignore() before using formatted input

linked list operation: insertion

use local pointer(*p), then make temp object (p = (cast) malloc(sizeof(struct [name])); Then get entries, then insert next link at beginning(p->next = head; head = p;)

fantastic four step 4

use size-m solution to construct size-n problem, this step is application-specific, sometimes we need the return values of multiple size-m problems

fflush(stdin)

use to remove delimiter before using getc(stdin) or getchar(stdin), as scanf leaves delimiter in buffer

const int i

variable with memory allocated, use & function to find address, compilation error if you try to modify, if you go around the compiler it can be modified but that is bad practice


Kaugnay na mga set ng pag-aaral

Course Point OB Practice questions

View Set

Financial Accounting | Chapter 8

View Set

Psychology Unit 2: sensation & perception, learning, memory

View Set

C++ 325 Quiz 5 Review, C++ 325 Quiz 4 Review, C++ 325 Quiz 3 Review, C++ 325 Quiz 2 Review, C++ 325 Quiz 1 Review, cecs 325 midterm

View Set

Vocabulaire des voyages: fiche d'étude

View Set

Chemistry: 19.1 Acid-Base theories (pages 647- 652)

View Set

AP WORLD HISTORY 4.5 ECONOMIC SYSTEMS

View Set

Ch 21 Mgmt of labor and birth risks

View Set