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

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
 #include  Using a directive to include a header file  Stdio.h = standard input output header file.
True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
Rossella Lau Lecture 9, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling 
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
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() 
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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() 
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
 data_type array_name [number-of-elements];  Two Dimensional Array array_type array_name [number_of_ROWS][number_of_COLUMNS];
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 C++ Syntax and Semantics, and the Program Development Process.
C Programming – Part 6 File Input and Output
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
CECS 121 Test 1. Functions allow you to group program statements under one name C and C++ are case-sensitive so main(), MAIN(), and Main() are all different.
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() 
Fundamentals of C++ Yingcai Xiao 09/03/08. Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
CECS 130 Final EXAM.  #include  Using a directive to include a header file  Stdio.h = standard input output header file.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Old Material escape sequences operator precedence printf() scanf() if() switch case &&,|| while, do-while, ++, -- functions New Material 1-D arrays string.
CECS 130 EXAM 1.  int main() { printf (“%c %c \n", 'a', 65); printf ("%d %ld\n", 1977, L); printf (" %10d \n", 1977); printf ("%010d \n", 1977);
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.
Pointers *, &, array similarities, functions, sizeof.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
 How a computer stores data in its internal memory  RAM (Random-Access Memory) - temporary  ROM (Read-Only Memory) – non volatile  Store data in bytes.
CECS 121 Final Test.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data.
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() 
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Exception Handling How to handle the runtime errors.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
C++ Lesson 1.
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Why exception handling in C++?
CECS 130 Mid-term Test Review
Computing with C# and the .NET Framework
Chapter 14: Exception Handling
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Variables, Identifiers, Assignments, Input/Output
CECS 130 Final Exam Review Session
Presentation transcript:

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

#include 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); system("pause"); } Output:

 fopen() returns a FILE pointer back to the pRead variable #include Main() { FILE *pRead; pRead = fopen(“file1.dat”, “r”); if(pRead == NULL) printf(“\nFile cannot be opened\n”); else printf(“\nFile opened for reading\n”); fclose(pRead); }

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

 Pretty basic.  Always close files when you use fopen.

 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);

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

Kelly11/12/866Louisville Allen04/05/7749Atlanta Chelsea03/30/9012Charleston Can you write a program that prints out the contents of this information.dat file?

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

 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. printf()

#include 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 ”); printf(“separated by spaces:”); scanf(“%s%s%f”, fName, lName, &gpa); fprintf(pWrite, “%s \t %s \t %.2f \n”, fName, lName, gpa); fclose(pWrite); }

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

 Summary  Include #include 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 <<

#include using namespace std; string name = “”; int main(void) { cout<<“What is your name?”; cin>>name; cout<<endl<<“Hello”<<name.c_str(); return 0; }

#include 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.c_str(); return 0; }

Test 1234 This is a test

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

TYPESIZEVALUES bool1 bytetrue (1) or false (0) char1 byte‘a’ to‘z’, ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, and so on int4 bytes-2,147,483,648 to 2,147,483,647 short2 bytes-32,768 to 32,767 long4 bytes-2,147,483,648 to 2,147,483,647 float4 bytes+ - (1.2 x 10^-38 to 3.4 x 10^38) double8 bytes+- (2.3 x 10^-308 to -1.7 x 10^308)

 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?

 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) < if(0<= (0<1))//true

 if(condition) statement; else if (condition) statement;  condition ? expr1 : expr2  ex. z = ( x > y ) ? y : x ;  Can we do next statement? (x>y) ? cout << “x is greater than y.” : cout << “x isn’t greater than y.”;

switch(expression){ case expr1: statement; break; case expr2: statement; break; case expr3: statement; break; default: statements break; }

 while (condition) { statements; You need to maintain a state to break loop. }  do { statements; You need to maintain a state to break loop. } while(condition);

 for (initialization; condition; expression) { statements; }  Incrementing: Prefix and Postfix int x = 5; int y = 6; int z = y++ //z=6, y=7 postfix operator int z = ++x //z=6, x=6 prefix operator

KeywordPurpose breakExits the nearest enclosing “switch” statement or iteration statement continueStarts the next loop of the nearest enclosing iteration statement gotoJumps to a particular place in your code returnEnds a function and returns a value

 Can you write a program that prints out the following?

for ( int count = 0; count < 10; count ++) { cout <<count<<“”; }

1. Write a conditional statement that will assign x/y to x if y doesn’t equal Write a while loop that calculates the summative of positive integers from 1 to some number n. 3. Write a conditional statement that assigns x*y if x is even; otherwise, if x is odd and y doesn’t equal 0, assign x to x/y; if neither of the preceding cases is true, output to the screen that y is equal to 0.

 Function declaration  Function definition  Function call

#include using namespace std; int add(int a, int b); 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; }

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

 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

 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

class ClassName { memberList }; memberList can be either data member declarations or method declarations

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

Return_type ClassName::methodName(argumentList) { methodImplementation }

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

 Arrays  Pointers

 data_type array_name [number-of-elements];  Two Dimensional Array array_type array_name [number_of_ROWS][number_of_COLUMNS];

 type* pointer_name;  ex. int my_int; int* my_int_pointer = &my_int; Assigns the address of my_int to the pointer

 Copying strings from one to another  char* strcpy(char* p, const char* q);  char s[6]; strcpy(s, “Hello”);  To combine strings  char* strcat(char* p, const char* q);  char s[12] = “Hello” strcat(s, “World”);

 To copy n characters from q to the of p.  char* strncpy(char* p, const char* q, int n);  char s [7] = “Say “; char t[] = “Hi”; strncpy (s, t, 2)

 Can you write a program using C++ that uses a FOR loop to initialize a 2D array that looks like the following {0,5,10,15}{0,2,4,6}

#include using namespace std; int main(){ int array[2][4],, row, column; for(row=0;row<2;row++) for(column=0;column<4;column++){ if(row==0) array[row][column]=column*5; else if(row==1) array[row][column]=column*2; } for(row=0; row<2; row++){ for(column =0; column <4; column ++) cout<<array[row][column]<<" "; cout<<endl; } system("pause"); return 0; }

 Basic framework for a program  How to Comment  How to Print  How to store variables  How to Print stored variables  How to find the size of a variable  How to convert from one data type to another  How to Declare Constants

 If statements  Conventional  Using conditional operator  Switch-case statements  Loops  While  Do-While  For  Branching statements

 How to declare and implement functions  How to create arrays  How to create pointers  Useful string functions  Classes

 //this is how you comment  /*this is how you comment */ Use for Multiple lines

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

 To call a namespace combat::fire()  Say (to avoid having to put combat:: every time using namespace combat; fire()

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

#include 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 { public: Dog(); // Constructors ~Dog(); // Accessors BREED GetBreed() const; void SetBreed(BREED); // Other methods // WagTail(); // BegForFood(); protected: BREED itsBreed; }; Animals MammalsReptiles HorseDog HoundTerrier YorkieCairn

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

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

#include 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 { 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"; } // 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; }

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

#include 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

#include 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 step Mammal move 2 steps. Dog move 5 steps

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

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

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

#include 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: 20 10

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

#include using namespace std; template 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 (i,j); n=GetMax (l,m); cout << k << endl; cout << n << endl; getchar(); return 0; } Output:

int i; 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 T GetMin (T a, U b) { return (a<b?a:b); } Then we could call the function like this: int i,j; long l; i = GetMin (j,l); Or simply: i = GetMin (j,l);

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

mypair myobject (115, 36); This same class would also be used to create an object to store any other type: mypair myfloats (3.0, 2.18);

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

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

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

 A way of handling Exceptions, example: #include 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'; } Output: Exception raised: Memory allocation failure!

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

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

 bad_alloc when new fail to allocate memory.  run_time_error errors occurring during excexution.  overflow_error and underflow_error deals with arithmetic overflow and underflow both derived from run_time_error class.

#include using namespace std; void MyFunc( void ); class CTest { public: CTest() {}; ~CTest() {}; const char *ShowReason() const { return "Exception in CTest class."; } }; class CDtorDemo { public: CDtorDemo(); ~CDtorDemo(); }; CDtorDemo::CDtorDemo() { cout << "Constructing CDtorDemo.\n"; } CDtorDemo::~CDtorDemo() { cout << "Destructing CDtorDemo.\n"; } 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"); }

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.

 Terminate the Program: Input files does not exist, no meaning of continue  Include code to recover from exception: User inputs wrong type, just inform user to re- enter correct format.  Log the error and continue: The program should be always running no matter what happened ( Monitoring satellites for example)

 By recursion we let a function call it self recursively until a break condition is met  The break condition is usually set in the base case of the problem  Example, factorial problem:  0!=1 this is the base case  n! = n(n-1)! If n>0, this is the general case  Always general case should reduce o base case

#include int main(){ int n=5; double fact=1; for(int i=1;i<=n;i++) fact=fact*i; cout<<fact; getchar(); }

#include double fact(int); int main(){ int n=5; double factVar=1; factVar=fact(n); cout<<factVar; getchar(); } double fact(int f) // Since the factorial grow fast, it’s better to make it { //double if(f==0)return 1; else return fact(f-1)*f; }

The Fibonacci sequence looks like this: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,... Fibonacci equations are: F(1) = 1 F(2) = 1 F(n) = F(n – 1) + F(n – 2)

#include int fib(int); // Fibonacci function prototype int main(){ int n=10; // The index of Fibonacci that we need to get cout<<fib(n); getchar(); } int fib(int x) { if(x==1 || x==2) return 1; else return fib(x-1)+fib(x-2); }

#include void hannoiTower(int,int,int,int); static int counter=0; int main(){ int disk=17; long beginTime = time(NULL); // Record starting time hannoiTower(disk,1,3,2); long endTime = time(NULL);// Record Ending time cout<<“”\n Time CPU spent in calculating:”<<endTime-beginTime; cout<<"\nNumber of disk moves were :"<<counter; getchar(); return 0; }

void hannoiTower(int count,int needle1,int needle3,int needle2) { if(count>0) { hannoiTower(count-1,1,2,3); cout<<"Move disk "<<count<<" from "<<needle1 <<" to "<<needle3<<"."<<endl; hannoiTower(count-1,2,3,1); counter++; // To calculate total number of disk moves } // which should be =2 Number of Disks -1 }

 Recursion functions executes more slowly that iteration version, and uses more memory and CPU time.  Choosing one method over another depends on the nature of the problem  Iterative method is easier than recursion, so unless the problem is inherently recursive, try to avoid recursion.

 Questions??  Good Luck from REACH in your Test