The document provides an overview of computer programming concepts, including hardware and software components, data hierarchy, and structured programming techniques. It covers various programming languages, types of errors, and the phases of program development, along with examples of control structures and functions in C programming. Additionally, it discusses libraries, formatted output, and string manipulation, emphasizing the importance of algorithms and recursion in programming.
The document provides an overview of computer programming concepts, including hardware and software components, data hierarchy, and structured programming techniques. It covers various programming languages, types of errors, and the phases of program development, along with examples of control structures and functions in C programming. Additionally, it discusses libraries, formatted output, and string manipulation, emphasizing the importance of algorithms and recursion in programming.
30317 – 143 COMPUTER PROGRAMMING INTRODUCTORY COMPUTER SYSTEMS, DATA HIERARCHY, ERRORS & ALGORITHMS ZANDER DE VILLIERS
HARDWARE & SOFTWARE: DATA HIERARCHY: LAYOUT OF PROGRAM:
» Bit: Binary digit of Single 0 or 1. 1. Block commentary.
» Peripherals: External devices which user interacts with. » Character: Pattern of bits. 2. Standard library includes. EX: Keyboard, mouse, printer. » Field: Series of characters/bytes to 3. User defined library includes. » Components: Parts of computer for operation of device. » represent something meaningful. 4. Declaration of Constants. EX: CPU, RAM, GPU » Record: Collection of related fields. 5. Declaration of global variables. » File: Group of related records. 6. List function prototypes. » Database: Collection organised 7. Main Function. » System Software: Programs designed run applications. data with easy access & manipulation. 8. Other user defined methods. EX: Operating System, Utility Software COMMENTS: DATA MEASUREMENT: » Application Software: Programs designed perform task. EX: Microsoft Word, Notepad++ /****************************************** Type Amount: * This is boxed comment. * Byte (B) 8 Bits (0/1) * Used for programs headings. * Kilobyte (KB) 1024 Bytes approximately doubles every year, without cost rising, ******************************************/ Megabyte (MB) 1024 Kilobytes Gigabyte (GB) 1024 Megabytes /* >>>>>>> Major Section Marker <<<<<<< */ Terabyte (TB) 1024 Gigabytes COMPUTER ORGANISATION: /* ------- Minor Section Marker ------- */ » ASCII: American Standard Code Information 1. Input Unit: Interchange. Converts characters into specific • Obtains information from user. //Line comment: describes single line. binary value. Limited to 256 char (1 byte). • EX: Keyboard, mouse, barcode scanners. 2. Output Unit: STRUCTURED PROGAM & PROGRAM CONTROL: SOFTWARE TECHNOLOGIES: • “Shipping” section that shows results to user. // >>>>>>> Selection Control <<<<<<< Refactoring: Reworking programs to make cleaner & • EX: Screen, Printer, Audio/Video easier to maintain while preserving functionalities. 3. Memory Unit – Random Access Memory (RAM): // ------- If/Else Statements ------- • Component stores data temporarily that computer if (CONDITION) { Design Patterns: Proven architectures for constructing is currently using to perform tasks. //1st Condition True flexible and maintainable object-orientated software. • Volatile, loses data when power is lost. } Encourage reuse to reduce time, money & effort. else if (CONDITION) { Software Development Kits (SDK): Tools and • Low capacity & expensive. //1st Condition False 4. Arithmetic & Logical Unit (ALU): documentation that developers use to program. //2nd Condition True • Performs arithmetic calculations. } TYPICAL C PROGRAM-DEVELOPMENT ENVIRONMENT: • Performs logical decisions. else { • ALU is usually found next to CPU. //1st Condition False PHASE 1: Creating/Editing Program:. 5. Central Processing Unit (CPU): //2nd Condition False • Type C program and store on secondary storage } device such hard disk or SSD. • Supervises & co-ordinates other sections of PC. • Filenames end with .c extension. • Multiprocessing: Have multiple cores to perform // ----- Switch Case Selection ----- switch (VAR) { PHASE 2: Preprocessor: many operations simultaneously. case ‘A’: • Invokes preprocessor that obeys special command • Multitasking: OS splits CPU time between programs //Code executed for case A called preprocessor directives. to appear as multiple programs run at once. break; //necessary to exit case • Manipulations consists inserting contents of other 6. Secondary Storage Unit: case ‘B’: files and various text replacements. • Components that store information permanently. //Code executed for case B PHASE 3: Compile: • Non-Volatile: Doesn’t lose data when power is lost. break; • Compiler translates C program into machine • Higher capacity & lower cost than RAM. default: //none of above cases language or object code. //inclusion default is optional • Syntax error occur when cannot translate code. TYPES OF PROGRAMMING LANGUAGES: break; PHASE 4: Linking: } 1. Machine Languages: • Object code produced has “holes” where libraries • PC only understands code which defined hardware. // >>>> While Iteration Structure <<<< such as standard or private was used. • Linker links programs object code with code for • Consists of strings of numbers 1/0 that perform //----- For Iteration Structure ----- missing functions to produce executable image. elementary instructions one at time. for (int i = 1; i <= 10; i++) { PHASE 5: Loading: • Object code. //Executed until false • Loader takes executable image from disk and 2. Assembly Languages: transfers to memory. /* if counter var is declared in • English like abbreviations to represent operations. loop, var will terminate after • Additional components from shared libraries that • Translated via assemblers into machine language. loop is completed */ support program are also loaded. • For humans to understand, computer can’t } PHASE 6: Execution: understand until converted to machine language. //Alternative for loop method: Program under control of CPU executes programs 3. High-Level Languages: int i = 1; //Declare Index Variable one instruction at time. for (i = 1; i <= 10; i++) { • Single statements can accomplish substantial tasks ALGORITHMS: //Code in Loop Inserted Here • Contains many statements known as source code. } • Translated via compilers into machine language. • Looks similar to English with basic math notations. // ----------- While Loop ----------- actions to execute and order in which actions while (CONDITION) { » Interpreter: Execute high-level languages programs //Executes until false } » Pseudocode: » directly. Avoids compilation delays, but code runs slower • Informal artificial language similar English helps » than compiled programs. // --------- Sentinel Loops --------- develop algorithms before being programmed. while (VAR != -1) { • Help think out program before written. TYPES OF ERRORS: //Executed until user enters -1 • Describe actions & decisions that will execute once Syntax Error: Programming fails follow programming //Allows Users to Enter Input as convert pseudocode to C. //Much as wanted language’s rules, doesn’t compile. » Flowcharts: Graphical representation of algorithm. scanf(“%d”, VAR) Logical Error: Occurs due program using incorrect //Code here using input algorithm to solve problem and produce incorrect output. } Runtime Error: When program crashes during runtime of // -- Do While Iteration Structure -- code due illegal operations or input. do { //executes code until false //code always run at least once. } while (i < 10); 30317 – 143 COMPUTER PROGRAMMING C PROGRAMMING: PROGRAM CONTROL, FUNCTIONS, LIBRARIES, INPUT & OUTPUT ZANDER DE VILLIERS
STRUCTURED PROGRAM DEVELOPMENT & PROGRAM CONTROL: MATH LIBRARY FUNCTIONS:
Iteration: do…while statement Sequence: Selection: Rounding round(f),ceil(f),floor(f) 3 while statement sqrt(x) √𝑥,cbrt(x), √𝑥 if statement Powers pow(x,y) 𝑥 𝑦 (single selection) Absolute Value abs(i), fabs(f) Division & Remainder fmod(x,y), modf(x,*ip) Trig Functions sin(x),cos(x),tan(x) asin(x), acos(x), atan(x) if …else statement Inverse Trig Functions 𝑥 atan2(x,y) tan−1 ( ) (double selection) 𝑦 for statement Hyperbolic Trig sinh(x),cosh(x),tanh(x) exp(x) 𝑒 𝑥 ldexp(x,n) 𝑥2𝑛 Exponential/Logarithm log(x) ln 𝑥 log10(x) log 𝑥 rand() % x 𝑥 → scaling factor Random Numbers srand(time(NULL)) random seed (needs <time.h>) » Different Condition Combinations: STRINGS & CHARACTERS: Cond 1 Cond 2 AND (&&) OR (||) NOT 1 (!=) » Character Arrays to Manipulate Strings: 1 1 1 1 0 1 0 0 1 0 0 1 0 1 1 Initialization: char ArrName[] = “string”; char ArrName[] = {‘s’,‘t’,‘r’,‘i’,‘n’,‘g’,‘\0’}; 0 0 1 0 1 Access string via pointer to first character. String’s value is (default is optional) » Break vs. Continue Statements: address of first character. break; → exits loop/switch statement early. switch statement (multiple selection) continue; → skips rest of loop & performs next iteration. » Null Termination Character \0: • Every string must end with null character. FORMATTED OUTPUT: TYPES OF VARIABLES: • If its overwritten, printing could continue past end of printf(“control-string”,other-arguments); 1. Local Variables: Only available in function where declared. string until another null character is encountered, puts(“string”); //includes \n at end. Initialize value every time entering function. accessing other parts of memory. sprintf(char *arr,“control-string”,arguments); 2. Static Variables: Only available in function where declared. » Arrays of Pointers: Used to form string of arrays where » Laterals & Escape Sequence: Only initialize value once, store values for duration execution. each pointer in array points to array of characters. \’ Outputs single quote (‘) character. 3. Global Variables: Available to all functions. Initialize once, const char *suit[3] = {"Str1", "Str2", "Str3"}; \” Outputs double quote (“) character. store values for duration of execution. Char * indicates each suit element is type “pointer to char.” \? Outputs question mark (?) character. \\ Outputs backslash (\) character. RECURSIVE FUNCTIONS: » Character-Handling Library: \a Produces sound or visual alert. • Functions calls upon itself directly/indirectly with base case. int isblank(int c) returns true if c is blank char (0 is false) \b Moves cursor back one position current line. • Divides problem into two pieces: Piece that functions know int isdigit(int c) returns true if c is digit (0 – 9) \f Moves cursor to next logical page’s start. how to do & smaller version of original problem. int isalpha(int c) returns true if c is letter (a – z or A – Z) \n Moves cursor to beginning of next line. • Launches recursive call to work on smaller problem. int isalnum(int c) returns true if c is digit or letter. \r Moves cursor to beginning of current line. • Sequence smaller problems must converge to base case. int isxdigit(int c) returns true if hex (0 – 9 or a – f or A – F) \t Moves cursor to next horizontal tab position. • Makes uses selection instead iteration. int islower(int c) returns true if c lowercase letter (a – z) \v Moves cursor to next vertical tab position. int isupper(int c) returns true if c uppercase letter (A – Z) » Conversion Specifiers: PASSING ARGUMENTS TO FUNCTIONS: int tolower(int c) changes c to lowercase letter (a – z) %d Display signed decimal integer. >>>>>>>>>>>>>> Pass by Value: <<<<<<<<<<<<<< int toupper(int c) changes c to uppercase letter (A – Z) %o Display unsigned octal integer. number = cubeByValue(number); //Pass Value int isspace(int c) returns true if c is ‘ ’ or lateral ‘\x’ Display unsigned decimal integer. int cubeByValue(int n) int iscntrl(int c) returns true if c control char (‘\x’) %u return n * n * n; //or pow(n, 3); int ispunct(int c) returns true if c not digit, letter, space %x Display unsigned hexadecimal integer. x for a-f & X for A-F returns true if c is printing character, %X >>>>>>>>>>>> Pass by Reference: <<<<<<<<<<<< int isprint(int c) including space. %hd Length modifiers to indicate short. cubeByRef(&number); //Pass Address returns true if c is printing character, %ld Length modifiers to indicate long. int isgraph(int c) void cubeByRef(int *nPtr) excluding space. %f Displays float value in fixed-point notation. *nPtr = pow(*nPtr, 3); %e Display float value in exponential notation » Standard-Utility Library: %E e for lowercase exp & E for uppercase exp. >>>>>>> Passing Arrays to Functions: <<<<<<< double strtod(const char *nPtr, char **endPtr); %g Display float value e/f depending value. void ModifyArray(int arr[], size_t SIZE) converts string nPtr to double. %G e for lowercase exp & E for uppercase exp. void ModifyElement(int e); //Only 1 Element long strtol(const char *nPtr, char **endPtr, int base); %c Display single character. converts string nPtr to long. %s Display string until encounters ‘\0’. OPERATOR PRECEDENCE CHART: priority top to bottom atof(char *str) Converts string pointed to double. %p Display pointer value as hexadecimal. Operator: Grouping: Type: atoi(char *str) Converts string pointed to integer. %% Displays ‘%’ character. () [] . -> ++ -- (postfix) left-to-right highest atol(char *str) Converts string point to long integer. + - ! & * ~ ++ -- (prefix) eight-to-left unary » Printing with Field Widths & Precision: * / % (remainder) + - (BODMAS) left-to-right assignment » String-Handling Library: %Xd X is field width for integer displayed. << >> (bitwise operators) left-to-right shifting strlen(char *str) Returns length of string. Y is precision of integer printed. < <= > >= left-to-right relational %.Yd strcop(s1, cs, n) Copy string cs to s1 for n chars. Default precision for integer is 1. == != left-to-right equality & (AND) ^ (XOR) | (OR) left-to-right bitwise strcat(str1, str2) concentrates both string into 1. %.Yf Y is maximum amount of decimal strcom(str1, str2) compares string alphabetically. && || left-to-right logical %.Ye value printed after 0. Default is 6. ?: x > y ? “true” : “false” left-to-right conditional %.Yg Y is max amount significant figures. TIME & DATE FUNCTIONS: = += -= *= /= %= |= ^= <<= >>= left-to-right assignment %.Ys Y is max characters printed string. time() Returns current time. FORMATTED INPUT: %X.Yf Combination: field width & precision. Returns difference in seconds. difftime(end,start) Specifying field widths & precision arguments: scanf(“format-string”,other-arguments); Makes use of time_t data type. printf(“%*.*f”, X, Y, VAR) int getchar(void); //returns next character sleep(int sec) Suspends program for seconds. → Field width X & Precision Y to float VAR Conversion Specifiers: Same as output except use &. clock() Measure CPU time use program Corresponding argument is pointer to variable. » Format Flags: SIZEOF OPERATOR: *sizeof operator arrays » Field Widths: Used to only read specific amount of characters. %-Xd Left-align output in specific field. printf(‘%zu’, sizeof(VAR)); changes when using VLA. » Scan Set: Inputs sequence of characters, looking only for %+d Display + sign for positive values. characters matching set. scanf(“%[string]”, Z); • Unary operator determines size in bytes of variable/type. % d Print space before positive values only. • Scan set stops when encounters character not in set. • Value returned has data type size_t. Cannot be used with + flag. %#o Prefix 0 to output value octal conversion. • Inverted scan set looks for characters not in set. [^string] • Run at compile time, doesn’t execute code inside parenthesis. %#X Prefix 0x to output value in hexadecimals. » Skipping Characters in Input Stream: char 1 int 4 short 2 %#f Force decimal point for float values. scanf(“%d*%d*%d”, &day, &month, &year); long 8 float 4 long long 8 %0Xd Pad field with leading zeros. //* is assignment suppressor operator double 8 long double 16 pointer 8 30317 – 143 COMPUTER PROGRAMMING C PROGRAMMING: ARRAYS, POINTERS, FILE PROCESSING, SORTING ALGORITHM & BIG O ZANDER DE VILLIERS
ARRAYS: SEARCHING ARRAYS: SORTING ALGORITHMS & BIG O:
» Linear Search: Program runs through entire array and
compares each value with search key until finds match. int n = 0; //counter 1. Order 1 O(1) Algorithms: Independent of number of » Declaration of Arrays: int Key = -1; //location of key elements in array. Constant number of comparisons. //Initialize Whole Array to 0 2. Order n O(n) Algorithms: Tests whether array’s first int n[100] = {0}; //Whole Array = 0 do { //loop through array to find match element is equal to any of array’s other elements. if (array[n] == key) { Key = n; Requires 𝑛 − 1 comparisons. Algorithm linear run time. //Initialize Array With List } 3. Order n-squared O(n2) Algorithms: Test whether any #define SIZE 5 //Max size of array } while ((Key == -1) && (n < size)); array elements is duplicated elsewhere in program. int n[SIZE] = {32, 27, 64, 18, 95}; Requires 𝑛2 ⁄2 − 𝑛⁄2 comparisons. Algorithm has » Binary Search: Compare middle value sorted array: quadratic run time. //Multidimensional Array - if key < middle, look through lower half of array. int Array2D[row][col] = {{1,2},{3,4},…}; » Bubble Sorting Algorithm: - if key > middle, look through upper half of array. void bubbleSort(int a[], int size) { //Determine Number of Elements in Array Repeats until key match is found. int i; //inner counter int n = sizeof(array) / sizeof(array[0]); while ((Key == -1)&&(low <= high)) { int pass; //outer counter int middle = (low + high) / 2; int hold; //temp var swap elements » Multidimensional (2D) Arrays: if (searchKey == Array[middle]) { //Outer Loop: Controls num of passes Column 0 Column 1 Column 2 Key = middle; for (pass = 1; pass < size; ++pass) { Row 0 a[0][0] a[0][1] a[0][2] } else if (searchKey < array[middle]) { //Inner Loop: Control num comparisons Row 1 a[1][0] a[1][1] a[1][2] high = middle – 1; //lower end array for (i = 0; i < size – 1; i++) { Row 2 a[2][0] a[2][1] a[2][2] } else { //Compare adjacent elements low = middle + 1; //higher end array if (a[i] > a[i + 1]) { } hold = a[i]; // > ascending ARRAYS & POINTERS: a[i] = a[i + 1]; // < descending » Arithmetic Operations for Pointers & Arrays: POINTERS: a[i + 1] = hold; • increment/decrement pointer: moves pointer to } } } } //Do not use brackets like this next/previous element in array. » Const Qualifier: • Addition/Subtraction: nPtr += 2; changes value 2 1. Non-Constant Pointer to Non-Constant Data: multiplied by size of object in array. » Declaration & Initialization: Both pointer and variable may change values & address. • Comparison: Equality operators can used if both Indirection – Referencing value through pointer. int *nPtr = &x; int x = 5; pointers point to same array. Address Operator (&): 2. Constant Pointer to Non-Constant Data: • Unary operator that returns address of its operand. Only value of var may change, address remains same. » Relationship Between Pointers & Arrays: • Must applied to variable, cannot applied values. const int *nPtr = &x; int x = 5; 1. Aiming Pointer to Arrays: Indirection Operator (*): 3. Non-Constant Pointer to Constant Data: • Pointers can initialized to first element of array: • Unary operator that gets value which pointer points to. Only address of pointer that var points to may change. • xPtr = x; or xPtr = &x[0]; //x is array • Also called dereferencing operator. int *nPtr = &x; const int x = 5; 2. Pointer/Offset Notation: Operators * and & are compliments of each other. 4. Constant Pointer to Constant Data: • Array name is like constant pointer to first element. Neither pointer nor variable may change values & int a = 5; //Variable with Value • Don’t modify array name, still points to first element. int *aPtr = &a; address. • *(xPtr + y) is same as *(x + y); Points to //Set Pointer to address of count const int *nPtr = &x; const int x = 5; array element x[y]. Parenthesis required operation. printf(‘Address: %p or %p’, &a, aPtr); » Void Pointers: 3. Pointer/Subscript Notation: //Both methods give address of var Pointers of same type can assigned to each other, except • Pointers can subscripted like arrays. printf(‘Values: %d or %d’ , a, *aPtr); when void pointer. Void pointers can’t dereferenced as size of • xPtr[y] = x[y] = *(x + y) = *(xPtr + y); //Both methods give value of var pointer is unknown, causes syntax error. FILE PROCESSING: WRITING/READING BINARY FILE: READ/WRITE FILE PROCESSING FUNCTIONS: int fgetc(FILE *stream); Reads char from file, equivalent getchar(); fwrite: Transfer bytes from int feof(FILE *stream); Returns true if end-of-file indicator of file. location in memory to file. void rewind(FILE *stream); Resets file position pointer to beginning file. » Files & Streams: char *fgets(char *str, int count, FILE *stream); Reads line from file. 1. Types of Streams: fwrite(&var, sizeof(var), int fscanf(FILE *stream, const char *format,…); Like scanf(); • Standard Input: Receives input from keyboard. numElements, fPtr); int fprintf(FILE *stream, const char *format,…); Like printf(); • Standard Output: Displays output on screen. fread: Transfer bytes from file to location in memory. DIFFERENT MODES FOR FILE PROCESSING: • Standard Error: Displays error message on fread(&var, sizeof(var),numElements,fPtr); screen. r Open file for reading. &var: Location transfer bytes from. 2. Types of Files: w Create file writing, discards current contents in file. sizeof(var):Number bytes allocate • Binary Files: a Append; create/open file for writing at end of file. If it isn’t array, number element (numElements) = 1 r+ Open file for update (reading & writing). Storage raw bytes unreadable to humans. w+ Create file for update, discards current contents in file. • Text Files: READING/WRITING STRUCTURES TO FILES: a+ Append; create/open file for update at end of file. Data stored characters and is human readable. rb Open file for reading in binary mode. 1. fwrite(&strct, sizeof(struct strct), wb Create file writing in binary, discards current contents file. » Opening/Closing Files: 1, fPtr); ab Append; create/open file for writing in binary at end of file. 2. fread(&strct, sizeof(struct strct), rb+ Open file for update (reading & writing) in binary mode. //Create Pointer to File 1, fPtr); wb+ Create file for update binary, discards current contents file. FILE *fPtr = NULL; 3. Array of Structures: Argument 1 changed to ab+ Append; create/open file in binary for update at end of file. //Open File, if cannot, then exit: number elements. fPtr = fopen(“<name>”,”<mode>”); RANDOM ACCESS FILES: DATA HIERARCHY: fclose(fPtr); //Close File • Access individual records without searching through other records. » Test Whether File Exists Before Using File: • Data can inserted/updated without destroying other data. FILE *fPtr = NULL; Writing Data: fseek(FILE *fPtr, long int offset, SEEK_X); if ((fPtr = fopen(“name.txt”,”r”))=NULL) { • fseek() sets file position pointer to specific position. puts(“file could not be opened”); • offset: File position to seek, relative to SEEK_X. else { - SEEK_SET: Seek starts at beginning of file. /* file processing in else */ - SEEK_CUR: Seek starts at current location in file. fclose(fPtr); //Close File - SEEK_END: Seek starts at end of file. } Reading Data: fread(&ptr, sizeof(x), 1, fPtr); 30317 – 143 COMPUTER PROGRAMMING C PROGRAMMING: STRUCTURES, LINKED LISTS, STACKS, QUEUES & BINARY TREES: ZANDER DE VILLIERS
STRUCTURES: STACKS:
» Structure Tag: Declare variables of structure.
struct employee { //Insertion Stacks (Push) //Deletion Stacks (Pop) char firstname[20]; » Members: Var declared with unique names. newPtr = malloc(sizeof(node)); tempPtr = topPtr; int age; Separate structures may contain members same name. newPtr->data = value; popValue = (*topPtr)->data; double Salary; » Self-Referential: Member that pointer to same struct newPtr->nextPtr = topPtr; topPtr = topPtr->nextPtr; struct employee *Ptr; type. Used build linked data structures. NULL pointer topPtr = newPtr; free(tempPtr); } lastname[20], empID; indicates end of data structure list. Variables of given structure can also defined by placing QUEUES: list of variables names after closing bracket.
» Accessing Structure Members: //Insertion Queue (Enqueue) //Deletion Queue (Dequeue) 1. Accessing via Member Name: StructName.MemName newPtr = malloc(sizeof(node)); value = headPtr->data; 2. Accessing via Pointer: namePtr->MemName newPtr->data = value; tempPtr = headPtr; newPtr->nextPtr = NULL; headPtr = headPtr->nextPtr; » Structures Passed to Functions: prevPtr->nextPtr = newPtr; free(tempPtr); • Pass Entire Structure by Value: Function cannot modify in caller. • Pass Pointer to Structure: Pass by reference, more efficient. LINKED LISTS: » TypeDef: • Mechanism to create synonyms for previously defined data types. • Commonly used create shorter names for struct types. • Using typedef doesn’t create new type, only alternative name. • Linear collection of self-referential structures linked. • Capitalize first letter of synonym to emphasize them. • Nodes linked to one another via pointers. typedef struct originalName SynonymName; • Linked lists accessed via pointer to first element, subsequent nodes accessed via link pointer member to current node. Link in last node is set to NULL » Enumeration Constants: • Values in enum start with 0, unless otherwise specified, and increment by 1. • Identifiers in scope must unique & set explicitly in definition by setting values. • Multiple enumeration members can have same constant value. enum suits = {“clubs” = 1,”spades”,”diamonds”,”hearts”};
BINARY TREES: //Searching Linked List:
int value = x; curPtr = startPtr; while (curPtr != NULL && value != curPtr->data) { sorting data, efficiently eliminating duplicate data items and compiling curPtr = curPtr ->nextPtr; //Cycle through Nodes //Insertion New Node: //Deletion List Node: newPtr = malloc(sizeof(Node)); struct treeNode { tempPtr = curPtr; newPtr->data = value; int data; prevPtr->nextPtr newPtr->nextPtr = NULL; struct treeNode *leftPtr; = curPtr->nextPtr; prevPtr->nextPtr = newPtr; struct treeNode *rightPtr; free(tempPtr); newPtr->nextPtr = curPtr; };
» Terminology: DYNAMIC MEMORY ALLOCATION:
• Root Node: First node of binary tree. 1. Malloc(): newPtr = malloc(numElements * sizeof(int)); • Left/Right Child: Node which left/right pointer points. //Dynamic Memory for Array Integers • Left/Right Subtree: left/right child and all children. newPtr = malloc(sizeof(struct strct); • Parent Node: Node of which specified node is one of children. //Dynamic Memory for Structure • Allocates memory for array with number of elements. » Sorted Binary Tree: • Starting address of memory block is stored in newPtr. • All values in any left subtree are smaller than value in parent node. 2. Free(): free(newPtr); • All values in any right subtree are greater than value in parent node. • Frees previously allocated memory. • Always free dynamically allocated memory to prevent memory leaks. » Order of Traversal Trees: • Set newPtr = Null; to prevent accessing wrong memory. 1. Inorder: at each node: void inOrder(TreeNodePtr treePtr) { I. Traverse node’s left subtree. if (treePtr != NULL) { Dynamic memory allocation is included in inOrder(treePtr->leftPtr); II. Process node’s value. printf(“%d”, treePtr->data); VARIABLE LENGTH ARRAYS: III. Traverse node’s right subtree. inOrder(treePtr->rightPtr); 2. Preorder: at each node: void preOrder(TreeNodePtr treePtr) { I. Process node’s value. if (treePtr != NULL) { printf(“%d”, treePtr->data); II. Traverse node’s left subtree. /* >>>>>>>>>>>>>>>>>>> VLA of 1D Array <<<<<<<<<<<<<<<<<<< */ preOrder(treePtr->leftPtr); III. Traverse node’s right subtree. preOrder(treePtr->rightPtr); int ArraySize = 0; //Size of 1D Array 3. Postorder: at each node: scanf(“%d”, &ArraySize); //Input Length of Array void postOrder(TreeNodePtr treePtr) { I. Traverse node’s left subtree. if (treePtr != NULL) { int Array1D[ArraySize]; //Declare 1D VLA with Variables II. Traverse node’s right subtree. postOrder(treePtr->leftPtr); /* >>>>>>>>>>>>>>>>>>> VLA of 2D Array <<<<<<<<<<<<<<<<<<< */ postOrder(treePtr->rightPtr); III. Process node’s value. int Row = 0; //Number of Rows of 2D Array printf(“%d”, treePtr->data); int Col = 0; //Number of Columns of 2D Array scanf(“%d %d”, &Row, &Col); //Input Length of Array STATIC VS. DYNAMIC MEMORY: int Array2D[row][col]; //Declare 2D VLA with Variables 1. Static Memory: ANSI STANDARD LIBRARIES: #INCLUDE <LIBRARY.h> • Memory requirements remains unchanged for entire program execution. • Example: Subscript arrays & Structures. <assert.h> <ctype.h> <errno.h> <float.h> <limits.h> 2. Dynamic Memory: <locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h> • Memory requirements change during execution of program. <stddef.h> <stdio.h> <stdlib.h> <string.h> <time.h> • Example: Linked lists, stacks, queues, trees. If using user defined library: #INCLUDE UserLibary.h