Introduction to C Final Review Chapters 1-6 & 13 Variables (Lecture Notes 2) Identifiers You must always define an identifier for a variable Declare and define variables before they are called in an expression or function. Syntax: DataType Name = value/expression; Ex: Int variableone = 1; Always include statement terminator (;) once finished with declarations. C is case sensitive Ex: variableone!= VariableOne Functions called in stdio.h cannot be capitalized: Main() vs main(). Capitalized Main () function call results in a compiler error. Do s Variables need both a name and a data type Names should be descriptive, and can include underscores to add clarification. Camel code is also good (ex: variabletypeone, vs variable_type_one) You can declare multiple variables using a comma (ex. int a, b, c;) Don'ts Cannot use key terms (typically terms that reference a function, or a useable command, such as the name array ) Ex names that are invalid : 1variable, _variable, array, int, Cannot begin with an underscore, number, or special characters ($%&) Data types Int, char, float, double, long float, short, size_t Type: Enum stands for enumeration, and will redefine variables to a user-invented data type. Ex: Enum Week = monday, tuesday, weds, thurs, fri, sat, sun Types have different sizes: [repl.it/@tiffanym1/data-types] Statements and Expressions A statement is: a complete unit of work, and is executed in sequential order.
Ex:y = y + x; An expression is: combination of variables, constants, operators, and functions. Ex: (a*(b+c) ) Arithmetic Operations Integer division: / symbol Does not include remainders, only valid for integers, and not floats Ex: 3/2 = 1; 2/2=1; Modulos % is the symbol It returns the remainder and is good for finding even and odd numbers Can relate to boolean statements, returning either 0 (false) or 1 (true); Order of Operation: Left to right reading: Basic arithmetic functions utilizing PEMDAS; Parentheses ( ) always first; For example: * and / is executed before + and - Right to Left reading: Increment (++) and Decrement (--) and Assignment (=) Post fix higher in operator precedence, Pre fix read secondarily Assignment operator (=) very lowest in precedence Some arithmetic expressions have been shortened in the code, such as adding and subtracting. Counter += 1 add one to counter Counter ++ or ++Counter add one to counter post or pre-expression Equalities and Relational Operators What values are considered true/false?: 1 = true, 0 = false; Use the == operator to check if a condition is true or false Repl Example Here Example of Incrementing and Decrementing a variable: int x = 0; int y = 1;
y++; x--; Example of Declaring a variable: int x = 0; Example of Adding Variables and Printing: int x = 0; int y = 1; printf("%d", x + y); prints out 1 Structured Programing(Lecture Notes 4/5) Algorithms A procedure for solving a problem How the action is executed in what order the actions are executed Flowcharts Flowcharts are graphical representations of algorithms. Pseudocode Not actual programming language An informal language explaining the solution in words in everyday english Ex: pseudocode If student s grade is greater than or equal to 60 Print Passed Pseudocode converted to C code If ( age >= 60) { printf( Passed \n ); } Sequential structure Statements executed one after another in sequential order Selection structure One or more conditions to be evaluated Ex: true/ false statements Conditional operator (?:) Composed of 3 Parts
Closely related to the if else statement Requires a condition, value is the condition is true, and a value if the condition is false, to be executedrepl.it example and explanation: https://repl.it/@anthony6151/conditionaloperatorexample Repetition structure A repetition statement allows you to repeat an action until a condition remains true. Repl Example : if loop Ex. 1- repl.it/kbrm Formulating Algorithms with Top-Down, Stepwise Refinement: repl.it/kcw6/3 Increment and Decrement Operators: repl.it/kbij/1 Program Control(Lecture Notes 6/7) World s first true computer? The ENIAC was a 27-ton, 1,800-square-foot bundle of vacuum tubes and diodes that was arguably the world s first true computer. the machine could execute 5,000 instructions per second Computer Organization Input receiving section obtains information (data and computer programs) from input devices (like keyboards). Output shipping section
takes information that the computer has processed and places it on various output devices to make it available for use outside the computer. Examples of output devices include printers and monitors Memory This rapid-access, relatively low-capacity warehouse section retains information that has been entered through the input unit making it immediately available for processing when needed Contains volatile info that is lost when the computer is powered off Secondary storage long-term, high-capacity warehousing section. Programs or data not actively being used by the other units normally are placed on secondary storage devices ALU (Arithmetic and Logic Unit) manufacturing section performs calculations, such as addition, subtraction, multiplication and division. It also contains the decision mechanisms CPU (Central Processing Unit) administrative section coordinates and supervises the operation of the other sections. Typical 6 Phases for C program s Creating a program: Six step process Six phases of programming/ what they do 1. Edit create and design code 2. Preprocessing: checks for errors to see if the code can be complied 3. Compilation: translates text to machine code a. starts from main function and reads instructions one by one 4. Linking saves the code in an executable form 5. Loading takes the executable image from disk and transfers to memory 6. Execution Runs the code Functions(Lecture Notes 8/9) Benefits of modularization?
Reusable modules Less modification Faster re-compilation Self-documenting Easier debugging Creating functions Definition Prototype Functions basically follow this format: return_type function_name( parameter list ) { body of the function } Return type include: int, char, void Void is used when you do not expect to return a value. Function name is what you use to call the function again. Parameter list is basically the placeholders of the function. Parameters vs Arguments Parameter - Parameter is basically the placeholder for the actual values in the function. Example: int add(int x, int y){} Int x and int y are the parameters of the function Arguments- The actual value of the variable that gets passed to the function. Example: int add(2,2); The twos will be placed into int x and int y so that the function will perform with the value 2 and 2. Generating random numbers Function used is rand(); in standard library <stdlib.h>, generates an integer between 0 and RAND_MAX. FORMULA: min +rand()%(max-min+1) 1+rand()%6; produces integers from 1 to 5 number 6 is called the scaling factor,1 is the shift from where we start from.
srand(); produces a random number with every run, if rand is used instead of srand then the program will run the same random number every time Storage class (how a variable should be stored) automatic storage duration - block-based (auto/register), static storage duration - program-based, but may not be accessible throughout the program (extern/static) ) https://www.studytonight.com/c/storage-classes-in-c.php Auto - instructions only variables, declares a local variable, rarely used Example: auto double x, y; Register - store a variable in a register of the CPU or cache memory, typically used in loops. Example: register int counter = 1; Extern - Static - Local variable that are known only in the function that they are defined at. Whenever the function is called the static variable will contain the last value it had. Example- static int count= 1; Scope- where the identifier can be referenced in a program, either throughout the function or in specific parts. Function scope- scope that is referenced in the function Cannot be referenced outside of the function. Mostly used in switch and goto statements. Ex. case A : File Scope- accessible in all functions. Example: Global variable, function definitions, and function prototypes. Starts from the declaration point to the end of the function. Declared outside of any function has file scope. Block Scope- Identifiers that are defined between {} or blocks. Local variables defined at the beginning of a function and function parameters.
In nested blocks. Local variables declared static still have block scope. Ex. int main (void) { Int x = 1; printf( Hello %d,x); } Function prototype scope- only used in the parameter list of a function prototype. Do not require names in the parameter list, only types are required and the compiler will ignore the name. Can be reused in functions anywhere. Ex. int maximum (int x, int y, int z); Recursive functions A function that calls itself either directly or indirectly through another function. Int fact( int n) { if (n <= 1) // base case return 1; else return n*fact(n - 1); } Repl examples here Preprocessor(Lecture Notes 10) Directive Definition does not have to be all Caps All preprocessor directives begin with a # Example: #include, #define #include: copy of a specified file is included #define: creates constants (symbolic constants) and operations (macros) represented as symbols #undef: discard the symbolic constants and macros created
The define needs to have an identifier and replacement text, which will replace the identifier Repl examples here #include <stdio.h> #include "filter.h" #define SIZE 10 Arrays(Lecture Notes 11/12) Arrays Definition A group of memory locations with the same name and same type Type arrayname [arraysize ]; The arraysize must be an integer constant greater than zero Array Names Contains only letters, digits, and underscores. Cannot begin with a digit Multiple-subscripted arrays (multidimensional arrays) Determining the size of an array: sizeof(arr)/sizeof(arr[0]); Represents tables of variables consisting of information arranged in rows and columns Must specify two subscripts: The first identifies the element s row The second identifies the element s column Array[Row][Column] = { {1, 2}, {3, 4} }; Sorting Techniques
Bubble Sort (Sinking Sort) https://repl.it/@sileadercj/bubblesort Repeatedly steps through the list to be sorted Compares each pair of adjacent items and swaps them if they are in the wrong order The pass through the list is repeated until no swaps are needed, which indicate that the list is sorted Passing Arrays to Functions To pass an array argument to a function, specify the name of the array without any brackets. Example: Int Array[24]; Function(Array, 24) Searching Arrays Used to determine whether an array contains a value matches a certain key value Methods Linear Search Compares each element of the array with the search key Works well for small or unsorted arrays This method is inefficient for larger arrays Binary Search If the array is sorted, the high-speed binary search technique can be used Definition A character array Can be initialized using string literals Example: char string1[] = hello ; String arrays can be initialized with character constants in an initializer list This can be tedious For example; char string1[] = {'f', 'i', 'r', 's', 't', '\0'}; \0
Repl example here https://repl.it/@bilbobaggins1/dice-roll-gen-array-example