REACH CECS 130 Final Test Review - PowerPoint PPT Presentation

1 / 88
About This Presentation
Title:

REACH CECS 130 Final Test Review

Description:

REACH CECS 130 Final Exam Test Review – PowerPoint PPT presentation

Number of Views:267
Avg rating:3.0/5.0
Slides: 89
Provided by: kmn8
Category:

less

Transcript and Presenter's Notes

Title: REACH CECS 130 Final Test Review


1
REACH CECS 130 Final Test Review
2
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()

3
Variable Types
TYPE SIZE VALUES
bool 1 byte true (1) or false (0)
char 1 byte a toz , A to Z, 0 to 9, space, tab, and so on
int 4 bytes -2,147,483,648 to 2,147,483,647
short 2 bytes -32,768 to 32,767
long 4 bytes -2,147,483,648 to 2,147,483,647
float 4 bytes - (1.2 x 10-38 to 3.4 x 1038)
double 8 bytes - (2.3 x 10-308 to -1.7 x 10308)
4
Control Statements Boolean Operators
  • What do each of the following evaluate to?
  • 1. long elves 8
  • int dwarves 8
  • if(elvesdwarves) //true or false?
  • if(elves!0) //true or false?
  • 2. int elves 4
  • int dwarves 5
  • if(dwarves gt (2/3)) //true or false?
  • 3. if(0 lt x lt 99) //true or false?
  • 4. if(0lt (0lt1))//true or false?

5
Control Statements Boolean Operators -Answers
  • What do each of the following evaluate to?
  • 1. long elves 8
  • int dwarves 8
  • if(elvesdwarves) //true
  • if(elves!0) //true
  • 2. int elves 4
  • int dwarves 5
  • if(dwarves gt (2/3)) //true
  • 3. if(0 lt x lt 99) //true TRUE (1) and FALSE (0)
    lt 99
  • 4. if(0lt (0lt1))//true

6
If statements
  • if(condition)
  • statement
  • else if (condition)
  • statement
  • condition ? expr1 expr2
  • ex. z ( x gt y ) ? y x
  • Can we do next statement?
  • (xgty) ? cout ltlt x is greater than y. cout ltlt
    x isnt greater than y.

7
Switch-case statements
  • switch(expression)
  • case expr1
  • statement
  • break
  • case expr2
  • statement
  • break
  • case expr3
  • statement
  • break
  • default
  • statements
  • break

8
Loops
  • 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)

9
Loops
  • for (initialization condition expression)
  • statements
  • Incrementing Prefix and Postfix
  • int x 5
  • int y 6
  • int z y //z6, y7 postfix
    operator
  • int z x //z6, x6 prefix
    operator

10
Branching statements
Keyword Purpose
break Exits the nearest enclosing switch statement or iteration statement
continue Starts the next loop of the nearest enclosing iteration statement
goto Jumps to a particular place in your code
return Ends a function and returns a value
11
FOR LOOP TEST
  • Can you write a program that prints out the
    following?
  • 0 1 2 3 4 5 6 7 8 9

12
Answer
  • for ( int count 0 count lt 10 count )
  • cout ltltcountltlt

13
Other Challenge questions for Loops
  1. Write a conditional statement that will assign
    x/y to x if y doesnt equal 0.
  2. Write a while loop that calculates the summation
    of positive integers from 1 to some number n.
  3. Write a conditional statement that assigns xy if
    x is even otherwise , if x is odd and y doesnt
    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.

14
How to declare and implement functions
  • Function declaration
  • Function definition
  • Function call

15
  • include ltiostreamgt
  • using namespace std
  • int add(int, int)
  • int main(void)
  • int number1, number2
  • cout ltlt Enter the first value to be summed
  • cin gtgt number1
  • cout ltlt \nEnter the second
  • cin gtgt number2
  • cout ltlt \n The sum is ltlt add (number1,
    number2) ltltendl
  • int add(int a, int b)return ab

16
Functions Challenge
  • Write a function, called multiply that multiplies
    two numbers and returns the result

17
Union
Output 9 3.1416
  • include ltstdio.hgt
  • includeltstdlib.hgt
  • union NumericType
  • int iValue
  • long lValue
  • double dValue
  • int main()
  • union NumericType Values // iValue 10
  • Values.iValue9
  • printf("d\n", Values.iValue)
  • Values.dValue 3.1416
  • printf("f\n", Values.dValue)
  • system("pause")

18
Sizeof()
19
Malloc()
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
20
free()
21
Calloc and Realloc()
  • 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))//allocat
    e 10 integers instead of 5
  • if (n1!NULL)
  • nn1
  • else printf("Out of memory!")
  • realloc() returns null if unable to complete or a
    pointer to the newly reallocated memory.

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

23
fopen(file name, Mode)
  • fopen() returns a FILE pointer back to the pRead
    variable

include ltcstdiogt 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(p
Read)
24
What does this code do?
  • int main ()
  • FILE pFile
  • char c
  • pFilefopen("alphabet.txt","wt")
  • for (c 'A' c lt 'Z' c)
  • putc (c , pFile)//works like fprintf
  • fclose (pFile)
  • return 0

25
Common Text File Modes
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 create new
r Open a file for read/write read from start error
w Create a file for read/write destroy contents create new
a Open a file for read/write write to end create new
b Combined with any mode enables user to work with binary files.(rb, wb, rb, etc.)
26
fclose(file pointer)
  • Pretty basic.
  • Always close files when you use fopen.

27
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, ss, name, hobby)

28
include ltstdio.hgt Main() FILE
pRead char name10 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)
29
Quiz
Kelly 11/12/86 6 Louisville Allen 04/05/77 49 At
lanta Chelsea 03/30/90 12 Charleston
Can you write a program that prints out the
contents of this information.dat file?
30
  • include ltstdio.hgt
  • Main()
  • FILE pRead
  • char name10
  • char birthdate9
  • float number
  • char hometown20
  • pRead fopen(information.dat, r)
  • if( pRead NULL )
  • printf( \nFile cannot be opened\n)
  • else
  • fscanf( pRead, ssfs, name,
    birthdate, number, hometown )
  • while( !feof(pRead) )
  • printf( s \t s \t f \t
    s\n, name, birthdate, number, hometown )

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

32
  • include ltstdio.hgt
  • Main()
  • FILE pWrite
  • char fName20
  • 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(ssf, fName, lName, gpa)

33
Quiz
  • 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 ?

34
C Input/Output
  • Summary
  • Include include ltiostreamgt 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 ltlt

35
C Input/Output Example
  • include ltiostreamgt
  • includeltstringgt
  • using namespace std
  • string name
  • int main(void)
  • coutltltWhat is your name?
  • cingtgtname
  • coutltltendlltltHelloltltname.c_str()
  • return 0

36
Can you predict the printout?
  • include ltiostreamgt
  • using namespace std
  • int x 25
  • string str2 This is a test
  • int main( void )
  • coutltltTestltlt1ltlt2ltlt3
  • coutltlt25 7ltltendlltltstr2.c_str()
  • return 0

37
Answer
  • Test 1234
  • This is a test

38
OOP
  • 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

39
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

40
Declaring Classes
  • class ClassName
  • memberList
  • memberList can be either data member declarations
    or method declarations

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

42
Creating Methods
  • Return_type ClassNamemethodName(argumentList)
  • methodImplementation

43
Methods Creation Example
  • //draws the bow
  • Void Bowdraw()
  • drawn true
  • coutltlt The ltltcolorltltbow has been
    drawn.ltltendl

44
Advanced Data Types
  • Arrays
  • Pointers

45
How to create arrays
  • data_type array_name number-of-elements
  • Two Dimensional Array
  • array_type array_name number_of_ROWSnumber_of_C
    OLUMNS

46
How to create pointers
  • type pointer_name
  • ex. int my_int
  • int my_int_pointer my_int
  • Assigns the address of my_int to the pointer

47
Useful string functions
  • Copying strings from one to another
  • char strcpy(char p, const char q)
  • char s6
  • strcpy(s, Hello)
  • To combine strings
  • char strcat(char p, const char q)
  • char s12 Hello
  • strcat(s, World)

48
Useful string functions
  • 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)
  • Output
  • Hiy

49
Challenge question
  • 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,150,2,4,6

50
Answer
  • includeltiostreamgt
  • using namespace std
  • int main()
  • int array24, , row, column
  • for(row0rowlt2row)
  • for(column0columnlt4column)
  • if(row0)
  • arrayrowcolumncolumn5
  • else if(row1)
  • arrayrowcolumncolumn2
  • for(row0 rowlt2 row)
  • for(column 0 column lt4 column )
  • coutltltarrayrowcolumnltlt" "
  • coutltltendl
  • system("pause")
  • return 0

51
Basics of C
  • 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

52
Inheritance
  • class aClass // Base class
  • public
  • int anInt
  • class aDerivedClass public aClass //Derived
    class
  • protected
  • float aFloat

53
Inheritance for Mammals Kingdome
include ltiostream.hgt 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
Mammals
Reptiles
Horse
Dog
Hound
Terrier
Yorkie
Cairn
54
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.

55
Overriding vs. Overloading functions
56
Overriding Functions
  • 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.

57
Overriding example
  • include ltiostream.hgt
  • enum BREED YORKIE, CAIRN, DANDIE, SHETLAND,
    DOBERMAN, LAB
  • class Mammal
  • public
  • // constructors
  • Mammal() cout ltlt "Mammal constructor...\n"
  • Mammal() cout ltlt "Mammal destructor...\n"
  • //Other methods
  • void Speak()const cout ltlt "Mammal sound!\n"
  • void Sleep()const cout ltlt "shhh. I'm
    sleeping.\n"
  • protected
  • int itsAge
  • int itsWeight
  • class Dog public Mammal
  • public
  • // Constructors
  • Dog() cout ltlt "Dog constructor...\n"

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

59
Overloading example
  • includeltiostream.hgt
  • 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 x4, y5, rad3
  • coutltlt"The Square area is "ltltarea(x)
  • coutltlt"\nThe Triangle area is "ltltarea(x,y)
  • coutltlt"\nThe Circle area is
    "ltltarea(x,y,rad)
  • getchar()
  • return 0
  • int area(int x) // square area
  • return xx

Output The Square area is 16 The Triangle area
is 20 The Circle area is 28.26
60
Another overloading example
  • include ltiostream.hgt
  • class Mammal
  • public
  • void Move() const cout ltlt "Mammal move one
    step\n"
  • void Move(int distance) const
  • cout ltlt "Mammal move "
  • cout ltlt distance ltlt" _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 ltlt "Dog move 5
    steps.\n"
  • int main()

Output Mammal move one step Mammal move 2
steps. Dog move 5 steps
61
Virtual Functions
  • To call a function youve 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 ltlt "I'm doing something"
  • struct Derived2 public Base
  • void do_something()
  • cout ltlt "I'm doing something else"
  • int main()
  • Base pBase new Derived1
  • pBase-gtdo_something()//does something
  • delete pBase
  • pBase new Derived2
  • pBase-gtdo_something()//does something else

62
Another Example
int main() Mammal theArray5
Mammal ptr int choice, i for
( i 0 ilt5 i) cout ltlt
"(1)dog (2)cat (3)horse (4)pig " cin
gtgt 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
theArrayi ptr
for (i0ilt5i)
theArrayi-gtSpeak()
system("pause") return 0
includeltstdlib.hgt include ltiostream.hgt
class Mammal public
Mammal()itsAge(1) Mammal()
virtual void Speak() const cout ltlt "Mammal
speak!\n" protected int itsAge
class Dog public Mammal
public void Speak()const cout ltlt
"Woof!\n" class Cat public
Mammal public void Speak()const
cout ltlt "Meow!\n" class Horse
public Mammal public void
Speak()const cout ltlt "Winnie!\n"
class Pig public Mammal public
void Speak()const cout ltlt "Oink!\n"
  • 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!

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

64
Pointers to base class
  • include ltiostreamgt
  • using namespace std
  • class CPolygon
  • protected
  • int width, height
  • public
  • void set_values (int a, int b)
  • widtha heightb
  • class CRectangle public CPolygon
  • public
  • int area ()
  • return (width height)
  • class CTriangle public CPolygon
  • public

Output 20 10
65
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)

66
Function Template
Output 6 10.5
  • include ltiostreamgt
  • using namespace std
  • template ltclass Tgt
  • T GetMax (T a, T b)
  • T result
  • result (agtb)? a b
  • return (result)
  • int main ()
  • int i5, j6, k
  • float l10.5, m5.6, n
  • kGetMaxltintgt(i,j)
  • nGetMaxltfloatgt(l,m)
  • cout ltlt k ltlt endl
  • cout ltlt n ltlt endl
  • getchar()
  • return 0

67
Other Template cases
  • 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 ltclass T, class Ugt
  • T GetMin (T a, U b)
  • return (altb?ab)
  • Then we could call the function like this
  • int i,j
  • long l
  • i GetMinltint,longgt (j,l)
  • Or simply
  • i GetMin (j,l)

68
Class Template
  • include ltiostreamgt
  • using namespace std
  • template ltclass Tgt
  • class mypair
  • T a, b
  • public
  • mypair (T first, T second) // constructor
  • afirst
  • bsecond
  • T getmax ()
  • template ltclass Tgt
  • T mypairltTgtgetmax ()
  • T retval
  • retval agtb? a b
  • return retval
  • int main ()
  • mypair ltintgt myobject (100, 75)

Output 100
69
Templates cntd.
  • mypairltintgt myobject (115, 36)
  • This same class would also be used to create an
    object to store any other type
  • mypairltdoublegt myfloats (3.0, 2.18)

70
More on Templates
  • include ltiostreamgt
  • using namespace std
  • // class template
  • template ltclass Tgt
  • class mycontainer
  • T element
  • public
  • mycontainer (T arg) elementarg
  • T increase () return element
  • // class template specialization
  • template ltgt
  • class mycontainer ltchargt
  • char element
  • public
  • mycontainer (char arg) elementarg
  • char uppercase ()

Output 8 J
71
Errors and Exception Handling
  • 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.

72
Simple assert example
  • include ltstdio.hgt
  • include ltassert.hgt
  • 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 a10
  • int b NULL
  • int c NULL
  • ba
  • print_number (b)
  • print_number (c)
  • return 0

73
try/catch Exception handling
  • A way of handling Exceptions, example
  • include ltiostreamgt
  • using namespace std
  • int main()
  • char buf
  • try
  • buf new char512
  • if( buf 0 )
  • throw "Memory allocation failure!"
  • catch( char str )
  • cout ltlt "Exception raised " ltlt str ltlt
    '\n'

Output Exception raised Memory allocation
failure!
74
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
    inform us that this catch can catch an exception
    of type integer.
  • A catch block with ellipses()catches any type of
    exception.

75
C Exception Classes
  • 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.

76
More classes on Exception handling
  • 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.

77
Exception Example
void MyFunc() CDtorDemo D coutltlt "In
MyFunc(). Throwing CTest exception.\n" throw
CTest() int main() cout ltlt "In
main.\n" try cout ltlt "In try block,
calling MyFunc().\n" MyFunc()
catch( CTest E ) cout ltlt "In catch
handler.\n" cout ltlt "Caught CTest
exception type " cout ltlt E.ShowReason()
ltlt "\n" catch( char str )
cout ltlt "Caught some other exception " ltlt str ltlt
"\n" cout ltlt "Back in main. Execution
resumes here.\n" system("pause")
  • include ltiostreamgt
  • 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()

78
Output of previous example
  • 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.

79
Exception Handling Techniques
  • 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)

80
Recursion
  • 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 ngt0, this is the general case
  • Always general case should reduce o base case

81
Factorial wihout using Recursive
  • includeltiostream.hgt
  • int main()
  • int n5 double fact1
  • for(int i1iltni)
  • factfacti
  • coutltltfact
  • getchar()

82
Recursive version of factorial
  • includeltiostream.hgt
  • double fact(int)
  • int main()
  • int n5 double factVar1
  • factVarfact(n)
  • coutltltfactVar
  • getchar()
  • double fact(int f) // Since the factorial grow
    fast, its better to make it
    // double
  • if(f0)return 1
  • else return fact(f-1)f

83
Fibonacci sequence example
  • The Fibonacci sequence looks like this
  • 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,
    ...
  • Fibonacci equations are
  • F(1) 1F(2) 1F(n) F(n  1) F(n  2)

84
Fibonacci implementation
  • includeltiostream.hgt
  • int fib(int) // Fibonacci function prototype
  • int main()
  • int n10 // The index of Fibonacci that we
    need to get
  • coutltltfib(n)
  • getchar()
  • int fib(int x)
  • if(x1 x2) return 1
  • else
  • return fib(x-1)fib(x-2)

85
Hannoi Tower example
  • includeltiostream.hgt
  • void hannoiTower(int,int,int,int)
  • static int counter0
  • int main()
  • int disk17
  • long beginTime time(NULL) // Record
    starting time
  • hannoiTower(disk,1,3,2)
  • long endTime time(NULL)// Record Ending
    time
  • coutltlt\n Time CPU spent in
    calculatingltltendTime-beginTime
  • coutltlt"\nNumber of disk moves were
    "ltltcounter
  • getchar()
  • return 0

86
Hannoi function
  • void hannoiTower(int count,int needle1,int
    needle3,int needle2)
  • if(countgt0)
  • hannoiTower(count-1,1,2,3)
  • coutltlt"Move disk "ltltcountltlt" from
    "ltltneedle1
  • ltlt" to "ltltneedle3ltlt"."ltltendl
  • hannoiTower(count-1,2,3,1)
  • counter // To calculate total number
    of disk moves
  • // which should
    be 2Number of Disks -1

87
Recursion vs. Iterations
  • 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.

88
  • Questions??
  • Good Luck from REACH in your Test
Write a Comment
User Comments (0)
About PowerShow.com