Presentation is loading. Please wait.

Presentation is loading. Please wait.

CECS 130 Mid-term Test Review

Similar presentations


Presentation on theme: "CECS 130 Mid-term Test Review"— Presentation transcript:

1 CECS 130 Mid-term Test Review
CECS 130 Final Exam Review Spring, 2017 CECS 130 Mid-term Test Review REACH Provided by REACH – Resources for Academic Achievement Presenters: Spencer Goff & Timi Seton

2 To download this presentation…
TestReviews.html

3 Data File Hierarchy Entity Description Bit Binary digit, 0 or 1
Smallest value in a data file Byte Eight bits Stores a single character Field Grouping of bytes i.e a word, social security number Record Grouping of fields a single row of information, student name, age, ID, GPA File Grouping of records separate fields in a record using spaces, tabs, or commas

4 Dynamic Memory Four functions related to memory allocation that you need to know: malloc() realloc() calloc() free()

5 Dynamic Memory Example
#include <sense.h> main() //programming for temperature logging device | int *temptime; // temp/time log [HHMMTTT format] | int hist = 0; // # of readings have been taken | temp = (int *) calloc(10, sizeof(int)); // pre-allocate some memory | if (temptime == NULL) { // check if it worked | | send_alert(“Memory failed!”); // send alert if not | } | | while (reset_button == “LOW”) { // keep logging until reset hit | | if( temp_sense() != temptime[hist -1] ) { // check if temp has changed | | | if( !(hist % 10) ) { // check whether you need memory | | | | temptime=realloc(temptime,(sizeof(int)*(hist+10))); // if so, add more memory | | | | if (temptime == NULL) { // check if it worked | | | | | send_alert(“Memory is full!”); // send alert if not | | | | | break; // and exit process | | | | } | | | | temptime[hist] = sensor_output; // otherwise, log the temp. | | | | hist = hist + 1; // and account for the new entry | | | } | | } | store_log(temptime); // save the log to non-volatile memory | free(temptime); // free up RAM for reset processes to use | reset_device(); // start the device reset process } Explain that sense.h is a header file that contains functions like send_alert( ), temp_sense( ), store_log( ), etc. These are used to communicate with other parts of the device (the sensors, the screen, etc.) The program first builds a buffer of 10 memory slots. Then, as more datapoints are added, it allocates 10 more memory slots for itself (Reallocation can be a slow process, so you wouldn’t want to do it every time a new data point is added.) Once the device’s reset button is pressed, it saves the log to a flash drive and frees the memory it was using to temporarily store the data collected.

6 Data File Hierarchy Entity Description Bit Binary digit, 0 or 1
Smallest value in a data file Byte Eight bits Stores a single character Field Grouping of bytes i.e a word, social security number Record Grouping of fields a single row of information, student name, age, ID, GPA File Grouping of records separate fields in a record using spaces, tabs, or commas

7 fopen( ) fscanf( ) fclose( ) fprintf( ) Files in C C
FILE datatype: like a pointer datatype, but it points to a file’s location in memory. File functions: fopen( ) fscanf( ) fclose( ) fprintf( )

8 Intro Example C Contents of file “alphabet.txt”
#include <stdio.h> int main( ) { FILE * pFile; char c; pFile=fopen("alphabet.txt","w+"); for (c = 'A' ; c <= 'Z' ; c++) { fprintf(pFile, %c, c); } fclose (pFile); return 0; } //end main Contents of file “alphabet.txt” ABCDEFGHIJKLMNOPQRSTUVWXYZ

9 Common fopen( ) modes C Mode Meaning Already Exists Does Not Exist “r”
Open a file for reading read from start error “w” Create a file for writing destroy contents create new “a” Append to a file write to end “r+“ Open a file for read/write “w+“ Create a file for read/write “a+“

10 fopen(“file name”, “Mode”)
fopen() returns a FILE pointer back to the pRead variable #include <stdio.h> int main() { FILE *pRead; pRead = fopen(“file1.dat”, “r”); if(pRead == NULL) { printf(“\nFile cannot be opened\n”); } else { printf(“\nFile opened for reading\n”); return 0;

11 fclose(file pointer) Pretty basic.
Just releases the file from the program. But why is that important? Allows other programs to use the file once you are finished with it. If you don’t release it, the file will be stuck as “read-only” until your program quits. No other programs can make changes. E.g. That’s why, when you have a file opened up in Word, when you try to rename it in File Explorer, you get an error message saying that “the file cannot be renamed because it is open in another program” Also, I think your processor is optimized so that it will load an open file into RAM as to access it more quickly. In this case, releasing the file will also free up sweet, sweet memory space for you.

12 fscanf(FILE pointer, “data type”, variable in which to store the value)
Reads a single field from a data file “%s” will read a series of characters until a white space is found. I.e. it can do | fscanf(pRead, “%s%s”, name, hobby);

13 #include <stdio.h> int main() { FILE *pRead; char name[10];
pRead = fopen(“names.dat”, “r”); if( pRead == NULL ) printf( “\nFile cannot be opened\n”); else printf(“\nContents of names.dat\n”); fscanf( pRead, “%s”, name ); while( !feof(pRead) ) { printf( “%s\n”, name ); } return 0; fscanf example

14 Quiz Kelly 11/12/86 6 Louisville Allen 04/05/77 49 Atlanta
Chelsea 03/30/90 12 Charleston Can you write a program that prints out the contents of this information.dat file?

15 information.dat contents: Kelly 11/12/86 6 Louisville
#include <stdio.h> int main() { FILE *pRead; char name[10]; char birthdate[9]; float number; char hometown[20]; pRead = fopen(“information.dat”, “r”); if( pRead == NULL ) printf( “\nFile cannot be opened\n”); else fscanf( pRead, “%s%s%f%s”, name, birthdate, &number, hometown ); while( !feof(pRead) ) { printf( “%s \t %s \t %f \t %s\n”, name, birthdate, number, hometown ); } return 0; information.dat contents: Kelly 11/12/86 6 Louisville Allen 04/05/77 49 Atlanta Chelsea 03/30/90 12 Charleston Prints out information.dat

16 fprintf(FILE pointer, “list of data type”, list of values or variables)
The fprintf() function sends information (the arguments) to the file indicated by [FILE pointer]. Argument 2 is the data being input to the file. fprintf() works just like printf() as far as formatting the input goes.

17 #include <stdio. h> int main() { FILE
#include <stdio.h> int main() { FILE *pWrite; char fName[20]; char lName[20]; float gpa; pWrite = fopen(“students.dat”,”w”); if( pWrite == NULL ) printf(“File not opened\n”); else { printf(“Enter first name, last name, and GPA separated”); printf(“\nEnter data separated by spaces:”); scanf(“%s%s%f”, fName, lName, &gpa); fprintf(pWrite, “%s \t %s \t %.2f\n”, fName, lName, gpa); fclose(pWrite); } return 0; fprintf example

18 Data File Example #include <stdio.h> int main() { FILE *pRead;
char name[10]; pRead = fopen(“names.dat”, “r”); if( pRead == NULL ) { printf( “\nFile cannot be opened\n”); } else { printf(“\nContents of names.dat\n”); fscanf( pRead, “%s”, name ); while( !feof(pRead) ) { printf( “%s\n”, name ); return 0;

19 Data File Example #include <stdio.h> int main() { char name[10];
FILE *pRead; char name[10]; char birthdate[9]; float number; char hometown[20]; pRead = fopen(“information.dat”, “r”); if( pRead == NULL ) printf( “\nFile cannot be opened\n”); else { fscanf( pRead, “%s%s%f%s”, name, birthdate, &number, hometown ); while( !feof(pRead) ) { printf( “%s \t %s \t %f \t %s\n”, name, birthdate, number, hometown ); } return 0;

20 Input/Output in C++ C++ No more printf()! New syntax:
#include <iostream> using namespace std; int add(int, int); int main(void) { int number1, number2; cout << “ Enter the first value to be summed:\t”; cin >> number1; cout << “\n Enter the second number to be summed:\t”; cin >> number2; cout << “\n The sum is: ” << add(number1,number2) << “\n”; } int add( int a, int b ) { return a + b;

21 Control Statements C++ A refresher on control statements:
switch (expression) { case expr1: do this; break; case expr2: do that; ... default: do something; } A refresher on control statements: if (condition) { do this; } else if (different condition) { do that; ... else { do something; for (initialize; condition; expression) { do this; } do { this; } while (condition); while (condition) { do this; }

22 Control Statements C++ Examples: switch a%3 { case 2: a++; break;
cout << a; } Examples: if ( a == b ) { cout << b; } else if ( a == c ) { cout << c; else { cout << “error”; for (a = -10; a < 3; a++) { cout << “\n” << a; } do { a++; } while (a%245 == 0); while (a%245 == 0) { a++; }

23 Functions C++ Pretty much the same old thing:
#include <iostream> using namespace std; int add(int, int); int main(void) { int x = 3; int y = 7; cout << “The sum is: ” << add(x,y) << “.” << endl; } int add(int a, int b) { return a + b; Output: The sum is 10.

24 Function overloading C++
Not the same old thing. Now, you can call the same function for different datatypes. #include <iostream> using namespace std; void swap(int* a, int* b) { int temp = a; a = b; b = a; } void swap(char *a, char *b){ char temp = a; a = b; b = a; int main(void) { int x = 1; int y = 2; char m = “t”; char n = “v”; cout << “x=” << x << “, y=” << y << “, m=” << m << “, n=” << n << endl; swap( &x, &y ); swap( &m, &n ); cout << “x=” << x << “, y=” << y << “, m=” << m << “ ,n=” << n << endl; Output: x=1, y=2, m=t, n=v x=2, y=1, m=v, n=t

25 OOP C++ Declare classes Create objects 3 MAIN PRINCIPLES OF OOP
Data abstraction – hiding data members and implementation of a class behind an interface to prevent a user of the class from corrupting that data/implementation Encapsulation – each class represents a specific thing or concept. Multiple classes combine to produce the whole Polymorphism-objects can be used in more than one program

26 Classes Classes are general models from which you can create objects
Classes have data members, data types, and/or methods Classes should contain a constructor method and a destructor method

27 Declaring Classes C++ class ClassName { [memberList] }; [memberList] can be either data member declarations, datatype members, or method declarations

28 Class Declaration Example
Class Bow { //data member declarations string color; bool drawn; int numOfArrows; Bow(string aColor); //constructor ~Bow(); //destructor //methods void draw(); int fire(); };

29 Creating Methods C++ Return_type ClassName::methodName(argumentList) { methodImplementation }

30 Methods Creation Example
//draws the bow void Bow::draw() { drawn = true; cout<< “The “<<color<<“bow has been drawn.”<<endl; }

31 Union C++ #include <stdio.h> #include<stdlib.h> union NumericType { int iValue; long lValue; double dValue; }; int main() { union NumericType Values; // iValue = 10 Values.iValue = 9; printf("%d\n", Values.iValue); Values.dValue = ; printf("%f\n", Values.dValue); return 0; } Output: 9 3.1416

32 Inline function C++ An inline function is one in which the function code replaces the function call directly. #include <stdio.h> inline void test(void){ puts("Hello!");} int main () { test(); // This will be replaced with puts("Hello!") on run time return 0; }

33 Friend Functions C++ Friend declarations introduce extra coupling between classes Once an object is declared as a friend, it has access to all non-public members as if they were public A friend function of a class is defined outside of that class's scope

34 Namespaces C++ Used to create functions, classes , and variables of the same name. For example, say you have two classes that use the same function name: namespace combat { void fire() } namespace exploration {

35 Namespaces C++ To call a namespace, say: combat::fire()
Or, to avoid having to put “combat::” every time, add using namespace combat; to the top of the program and then use fire();

36 Inheritance C++ class aClass { // Base class public: int anInt; }; class aDerivedClass : public aClass { //Derived class protected: float aFloat;

37 Inheritance for Mammals Kingdom
#include <iostream.h> enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB }; class Mammal { public: Mammal(); // constructors ~Mammal(); //destructor //accessors int GetAge()const; void SetAge(int); int GetWeight() const; void SetWeight(); //Other methods void Speak(); void Sleep(); protected: int itsAge; int itsWeight; }; class Dog : public Mammal { Dog(); // Constructors ~Dog(); // Accessors BREED GetBreed() const; void SetBreed(BREED); // Other methods WagTail(); BegForFood(); BREED itsBreed; Animals Mammals Reptiles Horse Dog Hound Terrier Yorkie Cairn

38 Static vs. Automatic variables
All your declared variables are automatic. Static variables keep there values as long as they exist.

39 Private vs. Protected C++
Private members are not available to derived classes. You could make itsAge and itsWeight public, but that is not desirable. You don't want other classes accessing these data members directly. What you want is a designation that says, "Make these visible to this class and to classes that derive from this class." That designation is protected. Protected data members and functions are fully visible to derived classes, but are otherwise private.

40 Scope :: C++ Used to go up one level.
If you have a global and local variables with same name, and need to call global from local scope then you need to use ::VariableName

41 Default Arguments C++ int boxVolume(int length = 1, int width = 1,int height = 1) { return (length * width * height); } If the function was called with no parameters then the default values will be used.

42 Overriding Functions C++ When do we need to override functions?
If you are a programmer example in your slides. If we consider “Woof” of the dog as speak example. When a derived class creates a function with the same return type and signature as a member function in the base class, but with a new implementation, it is said to be overriding that method. The signature of a function is its name, as well as the number and type of its parameters. The signature does not include the return type.

43 Overriding example C++
#include <iostream.h> enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB }; class Mammal { public: // constructors Mammal() { cout << "Mammal constructor...\n"; } ~Mammal() { cout << "Mammal destructor...\n"; } //Other methods void Speak()const { cout << "Mammal sound!\n"; } void Sleep()const { cout << "shhh. I'm sleeping.\n"; } protected: int itsAge; int itsWeight; }; class Dog : public Mammal { // Constructors Dog(){ cout << "Dog constructor...\n"; } ~Dog(){ cout << "Dog destructor...\n"; } // Other methods void WagTail() { cout << "Tail wagging...\n"; } void BegForFood() { cout << "Begging for food...\n"; } void Speak()const { cout << "Woof!\n"; } // This function is overriding the base class Speak() function private: BREED itsBreed; int main() { Mammal bigAnimal; Dog fido; bigAnimal.Speak(); fido.Speak(); getchar(); return 0; }

44 Overloading Functions
When you overload a method, you create more than one method with the same name, but with a different signature. When you override a method, you create a method in a derived class with the same name as a method in the base class and the same signature.

45 Overloading example C++ Output: The square area is: 16
#include<iostream.h> int area(int x); // square area int area(int x,int y); //triangle area float area(int x,int y, int radius); //circle area int main() { int x=4, y=5, rad=3; cout << "The square area is :"<<area(x); cout << "\nThe triangle area is :"<<area(x,y); cout << "\nThe circle area is :"<<area(x,y,rad); getchar(); return 0; } int area(int x) { // square area return x*x; int area(int x,int y ) { //triangle area return x*y; float area(int x,int y, int radius) { //circle area return radius*radius*3.14; Output: The square area is: 16 The triangle area is :20 The circle area is: 28.26

46 Virtual Functions C++ To call a function you’ve overridden in a derived class you need to use virtual functions. struct Base { virtual void do_something() = 0; }; struct Derived1 : public Base { void do_something() { cout << "I'm doing something"; } struct Derived2 : public Base { void do_something() { cout << "I'm doing something else"; int main() { Base *pBase = new Derived1; pBase->do_something(); //does something delete pBase; pBase = new Derived2; pBase->do_something(); //does something else return 0;

47 Another VF Example C++ #include<stdlib.h> #include <iostream.h> class Mammal { public: Mammal():itsAge(1) { } ~Mammal() { } virtual void Speak() const { cout << "Mammal speak!\n"; } protected: int itsAge; }; class Dog : public Mammal { void Speak()const { cout << "Woof!\n"; } class Cat : public Mammal void Speak()const { cout << "Meow!\n"; } class Horse : public Mammal void Speak()const { cout << "Winnie!\n"; } class Pig : public Mammal void Speak()const { cout << "Oink!\n"; } int main() { Mammal* theArray[5]; Mammal* ptr; int choice, i; for ( i = 0; i<5; i++) cout << "(1)dog (2)cat (3)horse (4)pig: "; cin >> choice; switch (choice) case 1: ptr = new Dog; break; case 2: ptr = new Cat; case 3: ptr = new Horse; case 4: ptr = new Pig; default: ptr = new Mammal; } theArray[i] = ptr; for (i=0;i<5;i++) theArray[i]->Speak(); system("pause"); return 0; Output: (1)dog (2)cat (3)horse (4)pig: 1 (1)dog (2)cat (3)horse (4)pig: 2 (1)dog (2)cat (3)horse (4)pig: 3 (1)dog (2)cat (3)horse (4)pig: 4 (1)dog (2)cat (3)horse (4)pig: 5 Woof! Meow! Winnie! Oink! Mammal speak!

48 Virtual functions, When?
Only if you have to redefine a function in a Derived class that is already defined in Base Class, otherwise, it’s just extra resources when executed.

49 Pointers to base class C++ Output: 20 10 int main () {
class CPolygon { protected: int width, height; public: void set_values (int a, int b) width=a; height=b; } }; class CRectangle: public CPolygon int area () return (width * height); class CTriangle: public Cpolygon return (width * height / 2); int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; getchar(); return 0; } Output: 20 10

50 Templates C++ Used in place of a specific data type. For example, use a template to add data types together, whichever data type the user wishes (i.e. integers, floats)

51 Function Template Output: 6 10.5 C++
#include <iostream> using namespace std; template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () int i = 5, j = 6, k; float l = 10.5, m = 5.6, n; k = GetMax<int>(i,j); n = GetMax<float>(l,m); cout << k << endl; cout << n << endl; getchar(); return 0; Output: 6 10.5

52 Other Template cases C++
int i; long l; k = GetMax (i,l); This won’t work because our GetMax template (from the last slide) expects two arguments of the same type. But, if we did the following: template <class T, class U> T GetMin (T a, U b) { return (a<b?a:b); } Then we could call the function like this: int i, j; i = GetMin<int,long> (j, l); Or simply: i = GetMin (j, l);

53 Class Template Output: 100 C++
#include <iostream> using namespace std; template <class T> class mypair { T a, b; public: mypair (T first, T second) // constructor a=first; b=second; } T getmax (); }; T mypair<T>::getmax () T retval; retval = a>b? a : b; return retval; int main () mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; Output: 100

54 Templates cntd. C++ mypair<int> myobject (115, 36); This same class would also be used to create an object to store any other type: mypair<double> myfloats (3.0, 2.18);

55 More on templates Output: 8 J C++ // class template specialization:
class mycontainer <char> { char element; public: mycontainer (char arg) element=arg; } char uppercase () if ((element>='a')&&(element<='z')) element+='A'-'a'; return element; }; int main () { mycontainer<int> myint (7); mycontainer<char> mychar ('j'); cout << myint.increase() << endl; cout << mychar.uppercase() << endl; return 0; } #include <iostream> using namespace std; // class template: template <class T> class mycontainer { T element; public: mycontainer (T arg) element=arg; } T increase () return ++element; }; Output: 8 J

56 Errors and Exception Handling
Always check for points where your program could get an undesirable action. Programmer should be responsible for adding exception handling code to eliminate an unexpected end of execution. assert() is a function that checks if an expression meets certain conditions.

57 Simple assert example C++
#include <stdio.h> #include <assert.h> void print_number(int* myInt) { assert (myInt!=NULL); // make sure that a value had been assigned to myInt printf ("%d\n",*myInt); } int main () { int a=10; int * b = NULL; int * c = NULL; b=&a; print_number (b); print_number (c); return 0;

58 try/catch Exception handling
Output: Exception raised: Memory allocation failure! A way of handling exceptions, example: #include <iostream> using namespace std; int main() { char *buf; try { buf = new char[512]; if( buf == 0 ) throw "Memory allocation failure!"; } catch( char * str ) { cout << "Exception raised: " << str << '\n';

59 try/catch Exception handling
The catch block is only executed if an error was thrown in the try block. catch(data type); the data type in this case informs us that this catch can catch an exception of type integer. A catch block with ellipses(…)catches any type of exception.

60 C++ Exception Classes C++ Two classes derived from exception:
Logic_error Runtime_error Both classes are defined in the stdexcept header file. invalid_argument class deals with illegal arguments in function calls. The class out_of_range and length_error are another examples.

61 More classes on Exception handling
bad_alloc when new fails to allocate memory. run_time_error errors occurring during execution. overflow_error and underflow_error deals with arithmetic overflow and underflow both derived from run_time_error class.

62 Exception Example C++ void MyFunc() { CDtorDemo D; cout<< "In MyFunc(). Throwing CTest exception.\n"; throw CTest(); } int main() { cout << "In main.\n"; try { cout << "In try block, calling MyFunc().\n"; MyFunc(); catch( CTest E ) { cout << "In catch handler.\n"; cout << "Caught CTest exception type: "; cout << E.ShowReason() << "\n"; catch( char *str ) { cout << "Caught some other exception: " << str << "\n"; cout << "Back in main. Execution resumes here.\n"; system("pause"); #include <iostream> using namespace std; void MyFunc( void ); class CTest { public: CTest() {}; ~CTest() {}; const char *ShowReason() const { return "Exception in CTest class."; } }; class CDtorDemo { CDtorDemo(); ~CDtorDemo(); CDtorDemo::CDtorDemo() { cout << "Constructing CDtorDemo.\n"; CDtorDemo::~CDtorDemo() { cout << "Destructing CDtorDemo.\n";

63 Output of previous example
C++ In main. In try block, calling MyFunc(). Constructing CDtorDemo. In MyFunc(). Throwing CTest exception. Destructing CDtorDemo. In catch handler. Caught CTest exception type: Exception in CTest class. Back in main. Execution resumes here.

64 Exception Handling Techniques
Terminate the Program: Input files does not exist, no reason to continue Recover from exception: User’s input is not formatted correctly, just inform user to re-enter correct format. Log the error and continue: The program must run at all times anyway, just keep a note of what went wrong. ( E.g. monitoring satellites)

65 Recursion C++ A recursive function is one that calls itself. E.g.
int makeTen(int number) { number += number; while (number <10) { makeTen(number); }

66 Recursion C++ What are disadvantages to using a recursive function?
Memory-intensive – quickly fills up the stack. Hard to follow – humans don’t really think recursively. Can become infinite loops that are hard to fix. See point #2. So why use them? Compact code. Sometimes they cannot be avoided.

67 On the test… Some types of problems you will likely encounter:
True/False questions Fill-in-the-blanks questions Finding errors in programs Common mistakes on this test: Not appending lines of code with a semicolon (“;”) Forgetting to use semicolons when writing a FOR loop Forgetting to add an ampersand (“&”) to your variable parameter in SCANF functions (and mistakenly using the ampersand when using PRINTF) Mixing up * and & in general. Off-by-one errors when accessing an array, especially when using a FOR loop.

68 Test Success: The Night Before
Avoid Extensive Study Only Do a Brief Review Do Something Relaxing Get Plenty of Sleep Avoid Stress-Producing Situations Maintain a Positive Attitude

69 Test Success: Day of the Test
Get Off to a Good Start Arrive on Time (or Early!) Compose Yourself Do a Final Scan of Your Notes Maintain a Confident Attitude Eat breakfast if possible. Compose yourself = deep breaths, calm yourself, get super angry, whatever. Just get in your best test-taking state of mind. comic by KC Green (

70 But seriously, you all will do great.
Thanks for coming, and good luck! Make sure everyone signed in on the sign in sheet with their name and student ID number! (If you have not signed in, please do so before you leave!) This presentation was provided by REACH – Resources for Academic Achievement

71 To download this presentation…
TestReviews.html Make sure everyone signed in on the sign in sheet with their name and student ID number!


Download ppt "CECS 130 Mid-term Test Review"

Similar presentations


Ads by Google