PHY 107 – Programming For Science
Final Exam Wed., Dec. 16 th from 2:45PM – 4:45PM in OM110 For exam, plan on using full 2 hours If major problem, come talk to me ASAP Exam covers material from entire semester Open-book & open-note so bring what you’ve got Your cell phone, parents, & computers are not allowed Cannot collaborate with a neighbor on the exam Problems will be in a similar style to midterms
Positional Notation To convert d n... d 3 d 2 d 1 d 0 into decimal: From base-b d 0 * b 0 d 1 * b 1 d 2 * b 2 d 3 * b 3 … + d n * b n
Converting Decimal To Base-b General way to convert from decimal to base-b: While decimal number ≠ 0 Divide decimal number by b Move remainder to left end of answer Replace decimal number with quotient
Input Using scanf
Input Using fscanf and FILE*
Output using printf Already seen how to print text using printf printf(“Hello World\n”); printf(“%d years old”, age); Prints out whatever is placed between quotes Print variables’ values with specifier and adding after Use escape sequences for fancier text output \n newline (move to start of next line) \t tab (go to next column that is multiple of 8) \\ \ (backslash character)
Output using fprintf & FILE* File output easy to write text using fprintf FILE * fOut = fopen(fileName, “w”); fprintf(fOut,“Hello World\n”); fprintf(fOut,“%d years old”, age); Prints out whatever is placed between quotes Print variables’ values with specifier and adding after Use escape sequences for fancier text output \n newline (move to start of next line) \t tab (go to next column that is multiple of 8) \\ \ (backslash character)
Even Better Magic Identifiers for scanf and printf calls TypeSpecifier char%c int%i, %d long int%li, %ld float%f, %e, %E, %g, %G double%lf, %le, %lE, %lg, %lG cString%s
Priority of Operations Equations can become very complex * 6 * = …? Very Very strict order of operations used by computer ( ) Solve from inner- to outermost + (positive) & - (negative) Solve from right to left * & % & / (division) Solve from left to right + (addition) & - (subtraction) Solve from left to right use lots of parentheses My suggestion: use lots of parentheses
Compound Assignment Operators Short simple operators that allow us to be lazy Save some typing for several common actions Lowest priority operation; expression evaluated first OperatorEquivalent C++ Expression a += 2;a = a + 2;a = a + 2; b -= d;b = b – d;b = b – d; c *= ;c = c * ( ); d /= 0.3 * e;d = d / (0.3 * e);
Mathematical Functions Add #include at top of file All these functions return a value Will NOT change argument’s value sin( x ), cos( x ), tan( x ), asin( x ), atan( x ), log10( x ), sqrt( x ), log( x ), exp( x ), pow( x, y ), floor( x ), ceil( x )
Relational Operators < ( less than) > ( greater than) <= ( less than of equal to) >= ( greater than of equal to) != ( inequality ≠) == ( equality – if two things have same value) assignment (=) NOT the same as assignment (=)
if (…) statement First evaluates expression in parenthesis Add opening brace ( { ) after closing parenthesis Can now write all statements to execute Add closing brace ( } ) to show where if ends If expression false, execution restarts at that point If expression is true, executes code in block Skips over block, when expression is false
if – else if – else Usage Must begin with if statement at the start This is required; what would we be saying else to? Only Only required part of this entire process Can then have zero or more else if s Tests can be anything; do not have to be related Until one is true, will be examined one-by-one Execute 1 st clause where true expression is found Only at the very end can have else clause If nothing else matches then else is executed
Executing switch Statement 1. Evaluates expression 2. Finds matching case or default (if it exists) If no default, may not have match - skips switch 3. Execution starts at 1 st matching label Execution will continue until break; found Will continue into next case if break; is not hit 4. Restarts running after switch once break hit May reach end of switch without a break Continues running code after switch
while Loop while (expression) { statement;... } Evaluates expression to find its value If true, executes entire loop body Re-check after each pass through loop, only Continue with loop while expression checks true
for Loop
Function Definition
return Statement
Declaring Arrays
Mistakes with Arrays
String Theory!
Important String Functions strlen(s) Counts characters in s before null character strcpy(s,t) Copies characters in t into s. strcat(s,t) Appends t to end of s. strcmp(s,t) Returns negative int if s t, and 0 if s==t strupr(s) Converts all characters in s to uppercase strlwr(s) Converts all characters in s to lowercase strncpy(s,t,n) Copied first n characters from t to s
Opening a File 3
Reading & Writing Binary Data Computers find binary data easier, faster, & better Stores data as 0 s & 1 s it uses internally to record info Except for char s, nearly impossible for humans to read Specific functions needed to read/write binary Program can have data written using fwrite() fread() reads from file into your program
Reading & Writing Binary Data Computers find binary data easier, faster, & better Stores data as 0 s & 1 s it uses internally to record info Except for char s, nearly impossible for humans to read Specific functions needed to read/write binary Program can have data written using fwrite() fread() reads from file into your program All other functions read & write text
& and * Operators variable & operator gets the address of a variable Used only with variables Used only with variables, including array elements Types must match, no automatic promotion possible Use * for value at location targeted by pointer * could also be multiply so only used with pointers Exception is when variable declared To declare variable is a pointer, need the * double x, *y; y = &x; x = *y + 2;
Pointers versus Arrays Both types of variables store an address Can be assigned to one another if types match To access value, can either use * or [ index ] *p same as p[0] - they are "synonyms" in C Arithmetic works similarly - *(p+5) same as p[5] Do not get carried away exploiting this idea Unlike arrays, memory not reserved for pointer Arrays not used to alias other variables (usually)
Arrays vs. Pointers Arrays = Yams Sweet PotatoesPointers = Sweet Potatoes Yams Makes space at declaration Variable value is address Use [] to access entries Can also access using * Can be assigned a pointer Needs target to be useful Variable value is address Use * to access target Can also access using [] Can be assigned array Often use pointers & arrays interchangeably
malloc() and free() malloc(…) creates array on heap ptr = malloc( arrayLength * sizeof( entry type )); ptr should be pointer to entry type Can use literal, expression, or variable for arrayLength Array can be returned since heap outlives frame free(varName) to stop using memory Argument must be address of 0 th entry in array SHOULD SHOULD NOT USE ARRAY after it has been freed Within program can call free() at any time
Using struct s variables Can assign struct variables to one another Variables must be of identical struct types Copies value of all fields but still remain independent Locations will be same, since pointers & arrays aliased In all other situation, must use fields Cannot add, multiply, compare struct variables For any legal use, individual fields always available Arrays of struct s can also be declared Within the array, each entry is struct variable
“Subtle” Hint
For Final You can use on this final: Your textbook & notes At the same time, you may NOT use: Computer, calculator, cell phone, or similar Friends, Romans, countrymen or their ears
How to Prepare for Midterm DODON'T Redo activities, labs, weekly… Make cheat sheets for the test Review how parts of C/C++work Assume notes replace studying Ever, ever invade Russia in winter Assume you'll pass cause you're cute
How to Prepare for Midterm DODON'T Redo activities, labs, weekly… Make cheat sheets for the test Review how parts of C/C++work Assume notes replace studying Ever, ever invade Russia in winter Assume you'll pass cause you're cute
Final Exams Dec. 15, 12:30 – 1:30 in OM115 Mastery Exam for PHY107L: Dec. 15, 12:30 – 1:30 in OM115 Dec. 16, 2:45 – 4:45 in OM110 Final Exam for PHY107: Dec. 16, 2:45 – 4:45 in OM110