Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1010E Programming Methodology Tutorial 5 Macros and Recursion C14,A15,D11,C08,C11,A02.

Similar presentations


Presentation on theme: "CS1010E Programming Methodology Tutorial 5 Macros and Recursion C14,A15,D11,C08,C11,A02."— Presentation transcript:

1 CS1010E Programming Methodology Tutorial 5 Macros and Recursion C14,A15,D11,C08,C11,A02

2 Question 1

3 Breakdown the problem into small parts: For single experiment, we need a function to compute the return double futureValue( double lower, double upper, double initial) For simulation, we need to run 1000 exps and count how many percent will can earn double proportionHigher(double lower, double upper, double initial)

4 Question 1 Main function. We assume proportionHigher() is already implemented

5 Question 1 proportionHigher We assume futureValue is implemented!

6 Question 1 futureValue Note the trick of computing random double in range [lower, upper]

7 Question 1 When writing main function, we assume proportionHigher is written and works correctly When writing proportionHigher, we assume futureValue is written and works correctly This kind of thinking method is called wishful thinking Assume some functions are ready, you can focus more on how to use them to solve problem. If those function aren’t really implemented, we then implement them!

8 Question 2 Using SWAP to change two variables: Standard code for changing (x, y): t=x; x=y; y=t; Macro Version: #define SWAP(x,y) int t=x;x=y;y=t; Not correct, due to int t How to swap two variable without using temp variables ?

9 Question 2 Function Version: Will it work by calling: ? x = 10; y = 20; swap(x, y); Notice the Pass-By-Value nature of functions!!

10 Question 2(b) Find maximum value of 3 numbers: #define MAX(A,B) ((A) > (B) ? (A) : (B)) max=MAX(MAX(a, b), c) Note that parenthesis are important !! Macros vs. Functions? Macros has no local variables, easily mess up Program size increases Normally only 1 line No wishful thinking can be used, has to know implementation before calling Why do we use Macro?

11 Recursion When function calls itself, it is called recursion Problem solving with recursion Needs to identify that if a similar problem with smaller input value is solvable ? If it so, can we use that to solve our problem? It is essentially a special case of wishful thinking Recursive Program: A baseline (stopping condition) A recursive formula How to solve bigger problem using similar small problems

12 Question 3 (a)

13 Question 3 (b)

14 Question 3 (c)

15 Question 3 Exponent 1Exponent 2Exponent 3 13 5 128 8

16


Download ppt "CS1010E Programming Methodology Tutorial 5 Macros and Recursion C14,A15,D11,C08,C11,A02."

Similar presentations


Ads by Google