Top Banner
49

Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Jan 21, 2016

Download

Documents

Sharleen Waters
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.
Page 2: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.
Page 3: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Please enter how long your name is: 21Please enter your name:NawafHello Nawaf

Please enter how long your name is: -7Failed allocation memory

Page 4: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.
Page 5: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

int *n;int * n1;n=( int * ) calloc(5, sizeof(int)); // Reserves a block of memory for 5 integers

//Decide you need to reallocate more memory later in the program

n1= (int *) realloc(n, 10 * sizeof(int));//allocate 10 integers instead of 5if (n1!=NULL){

n=n1; }else printf("Out of memory!");

realloc() returns null if unable to complete or a pointer to the newly reallocated memory.

Page 6: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Function declarationFunction definitionFunction call

Page 7: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#include <iostream>using namespace std;

int add(int, int);

int main(void){

int number1, number2;cout << “Enter the first value to be summed:”;cin >> number1;cout << “\nEnter the second:”;

cin >> number2;cout << “\n The sum is: “ << add (number1, number2) <<endl;

}

int add(int a, int b){return a+b;}

Page 8: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Write a function, called multiply that multiplies two numbers and returns the result

Page 9: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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()

Page 10: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

fopen() returns a FILE pointer back to the pRead variable

#include <cstdio>

Main(){ FILE *pRead;

pRead = fopen(“c:\\folder1\\folder2\\file1.dat”, “r”);

if(pRead == NULL) printf(“\nFile cannot be opened\n”);else printf(“\nFile opened for reading\n”);fclose(pRead);

}

Page 11: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

int main (){ FILE * pFile; char c; pFile=fopen("alphabet.txt","wt"); for (c = 'A' ; c <= 'Z' ; c++) { putc (c , pFile);//works like fprintf } fclose (pFile); return 0;}

Page 12: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.
Page 13: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Pretty basic. Always close files when you use fopen.

Page 14: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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%s”, name, hobby);

Page 15: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#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) ) { // While end of file not reached

printf( “%s\n”, name ); // output content of name

fscanf( pRead, “%s”, name ); // scan from file next string

} fclose(pRead);}

Page 16: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Kelly 11/12/86 6 LouisvilleAllen 04/05/77 49 AtlantaChelsea 03/30/90 12Charleston

Can you write a program that prints out the contents of this information.dat file?

Page 17: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#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 ); }

fclose(pRead);}

Page 18: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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.

Page 19: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#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”);

elseprintf(“\nEnter first name, last name, and GPA ”);printf(“separated by spaces:”);

scanf(“%s%s%f”, fName, lName, &gpa);fprintf(pWrite, “%s \t %s \t % .2f \n”, fName, lName, gpa);fclose(pWrite);

}

Page 20: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Can you write a program that asks the user for their Name Phone Number Bank account balanceAnd then prints this information to a data file called accounts.dat ?

Page 21: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

/* exit example */ #include <stdio.h>#include <stdlib.h>int main () {

FILE * pFile; pFile = fopen ("myfile.txt","r"); if (pFile==NULL) {

printf ("Error opening file"); exit (EXIT_FAILURE);

} else {

/* file operations here */ }

return 0; }

Page 22: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

/* perror example */ #include <stdio.h> int main () { FILE * pFile; pFile=fopen ("unexist.ent","rb"); if (pFile==NULL)

perror ("The following error occurred"); else

fclose (pFile); return 0; }

Page 23: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

void swap (int *a, int *b) ;void swap (float *c, float *d) ;void swap (char *p, char *q) ;The other way is to have different

number of input parameters for the function

Page 24: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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.

Page 25: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Used to go out 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

Page 26: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

All your declared variables are automatic.

Static variables keep there values as long as they exist.

Page 27: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Declare classes Create objects

3 MAIN PRINCIPLES OF OOP Data abstraction – hiding data members and

implementation of a class behind an interface so that the user of the class corrupt that data

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

Page 28: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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

Page 29: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

class ClassName{

memberList};

memberList can be either data member declarations or method declarations

Page 30: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Class Bow{

//data member declarationsstring color;bool drawn;int numOfArrows;

Bow(string aColor); //constructor~Bow(); //destructor

//methodsvoid draw();int fire();

};

Page 31: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Return_type ClassName::methodName(argumentList)

{methodImplementation

}

Page 32: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

//draws the bowVoid Bow::draw(){

drawn = true;cout<< “The “<<color<<“bow has been drawn.”<<endl;

}

Page 33: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#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 = 3.1416; printf("%f\n", Values.dValue); system("pause");}

Output:93.1416

Page 34: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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;}

Page 35: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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

Page 36: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

class aClass // Base class{

public:int anInt;

}

class aDerivedClass : public aClass //Derived class

{protected:

float aFloat;};

Page 37: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#include <iostream.h>enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };class Mammal{public: Mammal(); // constructors ~Mammal(); //destructor //accessorsint GetAge()const;void SetAge(int);int GetWeight() const;void SetWeight();//Other methodsvoid Speak();void Sleep();protected:int itsAge;int itsWeight;};class Dog : public Mammal {public: Dog(); // Constructors~Dog(); // AccessorsBREED GetBreed() const; void SetBreed(BREED); // Other methods // WagTail(); // BegForFood(); protected: BREED itsBreed;};

Animals

Mammals

Reptiles

Horse Dog

HoundTerrie

r

Yorkie Cairn

Page 38: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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.

Page 39: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.
Page 40: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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.

Page 41: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#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 methodsvoid Speak()const { cout << "Mammal sound!\n"; }void Sleep()const { cout << "shhh. I'm sleeping.\n"; } protected: int itsAge; int itsWeight; };

class Dog : public Mammal {public: // Constructors Dog(){ cout << "Dog constructor...\n"; } ~Dog(){ cout << "Dog destructor...\n"; } // Other methodsvoid 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;}

Page 42: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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.

Page 43: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#include<iostream.h>

int area(int x); // square areaint area(int x,int y); //triangle areafloat 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: 16The Triangle area is :20The Circle area is: 28.26

Page 44: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#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:int itsAge;int itsWeight;};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"; }}; int main() {Mammal bigAnimal;Dog fido;bigAnimal.Move();bigAnimal.Move(2);fido.Move(8);// can I do this?fido.Move();return 0;}

Output:Mammal move one stepMammal move 2 steps.Dog move 5 steps

Page 45: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

To call a function you’ve overridden in a derived class you need to use virtual functions.

Example: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 delete pBase; return 0; }

Page 46: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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: 5Woof!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: int itsAge; };

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"; } };

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; }

Page 47: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

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.

Page 48: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

#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 () { 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:2010

Page 49: Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.

Questions??Good Luck from REACH in your Test