Home
Browse
Create
Search
Log in
Sign up
Upgrade to remove ads
Only $2.99/month
CSE 240 Ch 2
STUDY
Flashcards
Learn
Write
Spell
Test
PLAY
Match
Gravity
Terms in this set (149)
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)
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)
shortest and simplest program
main () {}
main()
main can take arguments and specify output, ex: double main (int argc, char a) { ...; return...}
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
%d
specify integer type
%f, %5.2f
floating point number, have 5 digits and 2 decimal places
%c
char
%s
string
%x
hexadecimal number
C/C++ allows direct access to memory address
true, can still use name if wanted & available
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
2D array of chars
can be treated as a 1-D array of strings
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)
endl
\n in C++
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
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
what is a program
algorithm (steps of data manipulation, emphasized by imperative) and data (object of manipulation)
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
data declaration
declaration binds name to location and gives type, scope, and qualifier of the value to the location
scope rule
scope of a variable starts at declaration point and extends to the end of current braces, need to be declared before use
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
types in C
char (1 byte=8 bits), int, float, double, void
copy array size 7 to size 6
places extra in memory somewhere, does not give an error (semantic)
C++ types
bool (boolean), wchar_t(wide-character, 2 bytes = 16 bits), char, int, float, double, void
C/C++ modifiers
signed, unsigned, short, long
char
-127 to 127 or 0 to 255, 8 bits
signed char
-127 to 127, 8 bits
unsigned char
0 to 255, 8 bits
int
-32,768 to 32,767 ; 16 bits
signed int
same as int, 16 bits
unsigned int
0 to 65,535, 16 bits
short int
-32,768 to 32,767 ; 16 bits
signed short int
same as short int, 16 bits
unsigned short int
same as unsigned int, 16 bits
long int
+- 2,147,483,647 ; 32 bits
signed long int
same as long int, 32 bits
unsigned long int
0 to 4,294,967,295 ; 32 bits
float
6 decimal digits of precision, 32 bits
double
10 decimal digits of precision, 64 bits
long double
10 decimal digits of precision, 64 bits
bool
true/false, 1,8 bits
wchar_t
same as unsigned int, 16 bits
byte
0 to 255, 8 bits
decimal
128 bits
String
16 bits each
Registers
D-flip flops, 32 registers at 32 bits each, 50-200ps(access time)
Cache
SRAM, 0.5GB, 0.5-2.5ns, $200-$500/GB
Main Memory
DRAM, 16GB, 50-70ns, $20-$75/GB
Secondary storage
Magnetic Disk, 2TB, 5-20ms, $0.20-$2/GB
memory is byte-addressable
each byte has its own address, address of int, float, and pointer must be multiples of 4
Arrays in C/C++
individual elements accessed by index, string is array of characters
sizeof
find number of bytes used
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
\0
null terminator (null character), automatically added to the end of a string
truncated initialization
char s2[4] = "alpha" ; -> a l p h ; size = 4
pointers are
IMPORTANT
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)
pointer vs memory incrementation
to increment pointer use p++, to increment what is in pointer current address use
p =
p + 1
*(p++)
increment address first, then access
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)
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)
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)
&
referencing memory, on right side only(r-value), returns r-value, unary operator
*
dereferencing, giving name, can be on both sides, (l-value), unary, returns an l-value
int *j = 0 means...
j is set to 0
use pointer to navigate array
pointer is faster than using numbers with initial element of array + change; more consecutively, not from beginning everytime
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
in-class exercise answers
1) b 2) a 3) a 4) d 5) c (slides on Bb)
when using an array, in a loop a-- will...
go to the previous value of array, regardless of type
printf("%s", array) will print
string of array, excluding the null terminator
(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++
t = (int*) malloc (40);
t[0] = 5;
t can be treated as array by memory allocation
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)
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
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'.
Assume this is a 32-bit environment, given a declaration: int a[10]; What is the size (in bytes) of the entire array?
40
What is NOT the purpose (functionality) of the forward declaration (prototype)?
to allow a function to return different types of values
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.
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.
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
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
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
typedef
typedef typename newname; makes a new name that becomes a synonym for the type of typename
ex) typedef char FlagType;
FlagType x = '10';
type construction and enum
typedef enum {false, true} boolean;
boolean x = false;
struct (structure)
like a class in java, but without methods;
struct person
{
char name[30];
long phone;
char id[12];
} p;
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();
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];
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)
Buffer maps
I don't really get it, buffer is a queue structure, \n turns into \0
flush buffer
cin.ignore() or fflush(stdin)
fflush(stdin)
use to remove delimiter before using getc(stdin) or getchar(stdin), as scanf leaves delimiter in buffer
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))
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
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 notation
->, pointer to structure (in Java the [obj].value is pointer)
pointer extra practice
do some!
pointer size in memory
always 4 bytes
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;)
linked list insertion to arbitrary position
create pointer to certain node, then do insertion operations fro that node instead of head
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 functions: search()
create as a struct, create local variable stack, 2 pointers, find target with bigger(first) pointer and return smaller(second) pointer
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
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
industry application: amazon.com recommendation list
frequently bought together items are made automatically
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)
function/procedure/subroutine
named block of code the must be explicitly called
function purpose
abstraction and reuse
functions
communicate with rest of the code using global/static variables, but more often parameters/return values
formal and actual parameters
formal parameter is local variables in the function, actual parameters are the actual variable/values
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
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
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
passing a structure into a function
call by pointer(*y parameter) creates new address, call by value(y parameter) uses same address
passing string address using pointer
char
getString(char
str)
char *p
p ->
char q[ ] = "morning"
q= "morning"
char *s = "hello"
s -> "hello"
recursion is important for 310
make sure you understand
Merge sort
2 recursive calls,
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
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)
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
fantastic four step 2
check stopping condition first, then enter recursion, often stopping condition and corresponding value is trivial
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);]
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
applying fantastic four
multiple examples in slides, insertion sort
sorting algorithms
2.8 in textbook
graph
more than one next node allowed
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
binary tree
any node can have at most 2 next nodes (child nodes), linked list is a tree, binary tree
full binary tree
has each node with 2 or 0
balanced binary tree
leaf nodes can only differ by one level, fast search (more than other binary trees) O(logn)
binary search tree
number in each node, ordered
preorder traversal
root-left-right
Inorder traversal
left-root-right
postorder traversal
left-right-root
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)
search speed is _____ important than insertion speed
more
HW 7/8: print forward/backward
print first in recursive call, print backward put print second at end of recursive call
binary tree search
also recursive
Google Big Table
extended binary search tree, B+ tree, keeps sorted data, all records stored in leaves, insert with red-black tree for balance
modules and packages
group programs to make a library,
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"
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
pointer memory space
always 4 bytes
THIS SET IS OFTEN IN FOLDERS WITH...
CSE240 - quizzes final
121 terms
CSE 240 Ch 1
52 terms
CSE 240 Final
161 terms
CSE 240 Chapter 3
49 terms
YOU MIGHT ALSO LIKE...
CSE 220 Exam
56 terms
Computer Applications for Business Exam 2 Rutgers…
86 terms
cs 172 final
55 terms
Computer Applications for Business Exam 2 Rutgers…
88 terms
OTHER SETS BY THIS CREATOR
CSE 463 Midterm
105 terms
CSE 470 midterm
40 terms
CPI 350 Midterm
107 terms
Test 1
26 terms