1 / 47

REACH CECS 130 Exam 2 Test Review

REACH CECS 130 Exam 2 Test Review. C - Files. Do you know the syntax for each of these, used to read and write to data files? Pointers: think of it as the memory address of the file fopen () fclose () fscanf () fprintf (). fopen (“file name”, “Mode”).

lars-barton
Download Presentation

REACH CECS 130 Exam 2 Test Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. REACH CECS 130 Exam 2 Test Review

  2. C - Files Do you know the syntax for each of these, used to read and write to data files? • Pointers: think of it as the memory address of the file • fopen() • fclose() • fscanf() • fprintf()

  3. fopen(“file name”, “Mode”) • fopen() returns a FILE pointer back to the pRead variable • #include <cstdio> • Main() • { • FILE *pRead; • pRead = fopen(“file1.dat”, “r”); • if(pRead == NULL) • printf(“\nFile cannot be opened\n”); • else • printf(“\nFile opened for reading\n”); • }

  4. What does this code do? int main () { FILE * pFile; char c; pFile=fopen("alphabet.txt","w");//Open with write access for (c = 'A' ; c <= 'Z' ; c++) { putc (c , pFile);//works like fprintf } fclose (pFile); return 0; }

  5. Common Text File Modes

  6. fclose(file pointer) • Pretty basic. • Always close files when you use fopen.

  7. 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 • can do fscanf(pRead, “%s\t%s”, name, hobby);

  8. #include <stdio.h> • 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 ); • fscanf( pRead, “%s”, name ); • } • }

  9. 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?

  10. #include <stdio.h> • 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 ); • fscanf( pRead, “%s%s%f%s”, name, birthdate, &number, hometown ); • } • }

  11. fprintf(FILE pointer, “list of data types”,list of values or variables) • The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes.

  12. #include <stdio.h> Main() { FILE *pWrite; char fName[20]; char lName [20]; float gpa; pWrite = fopen(“students.dat”,”w”); if( pWrite == NULL ) printf(“\nFile not opened\n”); else printf(“\nEnter 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); }

  13. C++ Input/Output • Summary • Include #include <iostream> directive at beginning of program • Use cin to take data from user • Use cout to display data on screen • Display multiple strings and integers in the same cout statement by separating items with <<

  14. C++ Input/Output Example #include <iostream> #include<string> using namespace std; string name = “”; int main(void) { cout<<“What is your name?”; cin>>name; cout<<endl<<“Hello ”<<name; return 0; }

  15. Can you predict the printout? #include <iostream> using namespace std; int x = 25; string str2 = “This is a test”; int main( void ) { cout<<“Test”<<1<<2<<“3”; cout<<25 %7<<endl<<str2; return 0; }

  16. Answer Test 1234 This is a test

  17. Data • How a computer stores data in its internal memory • RAM (Random-Access Memory) - temporary • ROM (Read-Only Memory) – non volatile • Store data in bytes • How you store data temporarily • Create variables based on fundamental types (bool, char, int, float) • constants: #define CONSTNAME value • sizeof()

  18. Variable Types

  19. Control Statements – Boolean Operators • What do each of the following evaluate to? 1. long elves = 8; int dwarves = 8; if(elves==dwarves) //true or false? if(elves!=0) //true or false? 2. int elves = 4; int dwarves = 5; if(dwarves > (2/3)) //true or false? 3. if(0 < x < 99) //true or false? 4. if(0<= (0<1))//true or false?

  20. Control Statements – Boolean Operators -Answers • What do each of the following evaluate to? 1. long elves = 8; int dwarves = 8; if(elves==dwarves) //true if(elves!=0) //true 2. int elves = 4; int dwarves = 5; if(dwarves > (2/3)) //true 3. if(0 < x < 99) //true …TRUE (1) and FALSE (0) < 99 4. if(0<= (0<1))//true

  21. OOP • Declare classes • Create objects • 3 MAIN PRINCIPLES OF OOP • Data abstraction – hiding data members and implementation of a class behind an interface . • 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

  22. Classes • Classes are general models from which you can create objects • Classes have data members either data types or methods • Classes should contain a constructor method and a destructor method • See handout for example of a program that utilizes a class

  23. Declaring Classes class ClassName { memberList }; memberList can be either data member declarations or method declarations

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

  25. Creating Methods Return_typeClassName::methodName(argumentList) { methodImplementation }

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

  27. Namespaces • Used to create functions, classes, and variables of the same name • Ex. Namespace combat { void fire() } Namespace exploration { void fire() }

  28. Namespaces • To call a namespace combat::fire() • Say (to avoid having to put combat:: every time using namespace combat; fire()

  29. Inheritance class aClass// Base class { public: intanInt; } class aDerivedClass : public aClass//Derived class { protected: float aFloat; };

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

  31. Private vs. Protected • 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.

  32. Overriding Functions • When do we need to override functions? • If you are a programmer example. • If we consider “Woof” of the dog as speak. • 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 overridingthat method.

  33. Overriding example • #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: • intitsAge; • intitsWeight; • }; • class Dog : public Mammal { • public: • // 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"; } • private: • BREED itsBreed; • }; • intmain() { • Mammal bigAnimal; • Dog fido; • bigAnimal.Speak(); • fido.Speak(); • getchar(); • return 0; • }

  34. 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.

  35. Overloading example #include<iostream.h> int area(int x); // square area int area(intx,int y); //triangle area float area(intx,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(intx,inty ) //triangle area { return x*y; } float area(intx,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

  36. Another overloading example #include <iostream.h> class Mammal { public: void Move() const { cout << "Mammal move one step\n"; } void Move(int distance) const{ cout<< "Mammal move "; cout<< distance <<" _steps.\n"; } protected: intitsAge; intitsWeight; }; class Dog : public Mammal { public: // You may receive a warning that you are hiding a function! void Move() const { cout << "Dog move 5 steps.\n"; } }; intmain() { Mammal bigAnimal; Dog fido; bigAnimal.Move(); bigAnimal.Move(2); fido.Move(8); fido.Move(); return 0; } // Can you spot any problem/s in the last 4 lines ? Output: Mammal move one step Mammal move 2 steps. Dog move 5 steps

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

  38. Another Example 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; break; case 3: ptr = new Horse; break; case 4: ptr = new Pig; break; default: ptr = new Mammal; break; } 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! #include<stdlib.h> #include <iostream.h> class Mammal { public: Mammal():itsAge(1) { } ~Mammal() { } virtual void Speak() const { cout << "Mammal speak!\n"; } protected: intitsAge; }; class Dog : public Mammal { public: void Speak()const { cout << "Woof!\n"; } }; class Cat : public Mammal { public: void Speak()const { cout << "Meow!\n"; } }; class Horse : public Mammal { public: void Speak()const { cout << "Winnie!\n"; } }; class Pig : public Mammal { public: void Speak()const { cout << "Oink!\n"; } };

  39. Virtual functions, When to use them? • 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.

  40. Pointers of type base class #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectanglerect; CTriangletrgl; 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; }

  41. Templates • 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)

  42. Function Template Output: 6 10.5 #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 () { inti=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; }

  43. Other Template cases inti; long l; k = GetMax (i,l); This would not be correct, since our GetMax function template 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: inti,j; long l; i = GetMin<int,long> (j,l); Or simply: i = GetMin (j,l);

  44. Class Template #include <iostream> usingnamespacestd; template <class T> classmypair { T a, b; public: mypair (T first, T second) { a=first; b=second;} T getmax(); }; template <class T> T mypair<T>::getmax () { T retval; retval = a>b? a : b; returnretval; } int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; } Output: 100

  45. Templates cntd. 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);

  46. More on Templates #include <iostream> using namespace std; // class template: template <class T> class mycontainer { T element; public: mycontainer (T arg) {element=arg;} T increase () {return ++element;} }; // class template specialization: template <> 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; } Output: 8 J

  47. Questions?? • Good Luck on your Test

More Related