UCLA CS 31 Lecture7 Post

42
Wednesday, October 27 th • Function Review • Program Design and Decomposition • Typecasting • If we have some time, we’ll start ASCII

description

Describing function design

Transcript of UCLA CS 31 Lecture7 Post

  • Wednesday, October 27th Function ReviewProgram Design and DecompositionTypecastingIf we have some time, well start ASCII

  • Function ReviewThe foo function computes the average of two numbers and:

    Returns the sum of the numbers.

    Sends back the average of the numbers in the third reference parameter.Whats wrong with it?

  • Function ReviewWhat does the following program print out?

    What is the value of credit after lines 1, 2 and 3 have executed.float credit;

    void charge(float amount){ if (amount

  • Function + Static Reviewfloat moving_avg(float cur) // avg of last 3{ static float s1,s2,s3;

    s1=s2; s2=s3; s3=cur;

    return((s1+s2+s3)/3);}

    int main(void){ float avg; avg=moving_avg(3); cout

  • Reference Reviewvoid Silly(int byValue, int &byReference){ byValue = 10; byReference = 20;}void main(){ int a = 5, b = 6;

    Silly(a,b); cout

  • Reference Reviewvoid Silly(int byValue, int &byReference){ byValue = 10; byReference = 20;}void main(){ int a = 5, b = 6;

    Silly(a,b); cout

  • void Silly(int byValue, int &byReference){ byValue = 10; byReference = 20;}void main(){ int a = 5, b = 6;

    Silly(a,b); cout

  • Programming Challengevoid main(void){ int eyes, ears; cin >> eyes >> ears; switch (eyes + ears) { case 0: cout
  • Top Down DesignToday were going to learn how to attack large programming problemsBy breaking a big problem down into smaller, more manageable components, we make it easier to solve.

  • Top Down DesignImagine if you were redecorating a bedroom

    Youd probably want to break up the task into a set of smaller steps:Remove all furniture. Remove carpet. Strip old wallpaper. Fix the drywall.Paint the room. Wallpaper the room. Lay new carpet. And each of these steps can be further refined

  • Top Down DesignBy decomposing this decorating problem, we can turn a big job into a set small, manageable tasks.In a similar fashion, we can decompose complex programs into simpler components.Learning how to decompose complex problems is a critical programming skill, and its difficult to master without lots of practice.

  • Top Down DesignThe game of 21 Pickup is a two-player gameWe start with a pile of 21 stonesPlayers take turns removing 1,2,or 3 stones from the pileThe player that removes the last stone wins

    Goal: Write a program that plays 21 Pickup

  • Top Down DesignIf this is your first time programming, its difficult to figure out where to startHow do you break the problem down?

  • Top Down Design ProcessStep 1: Understand the problems requirements

    A. What must your program do to be correct? B. What are the inputs to your program? C. What are the outputs from your program? D. Are there any special cases to consider?For class projects, well provide you with the requirements But in the real world youll often have to identify them yourself.

  • 21 Pickup Requirements?Will the computer:be one of the players orsimply run a game between two human players?And which player goes first?How will the program display the progress of the game?Will we use graphics or just simple text?How will the program prompt human player(s) for their moves?Come up with a detailed spec!What if the user enters an invalid move?What happens when a game is over?What algorithm will the computer player use to choose its moves?

  • Our RequirementsThe computer will play against a human playerThe human player will always go firstWhen the program starts, it will print out instructionsTo play 21 Pickup, each player blah blah blahThe computer will choose a random number of stones each roundThis is what the programs output should look like each round:There are X stones left.Please enter # of stones to remove: Then the user types in the number of stonesIf the user types an invalid number of stones, the program will:print Invalid # of stones. Try again.Prompt the user another timeThe computer takes Y stones.When one player wins, the program will display:The computer wins or The human winsAfter the game is over, the program will end

  • Top Down Design Process A. Break the problem up into simple componentsStep 2: Decompose the problem into independently solvable, smaller components B. Create a specification for each component:Identify inputs, outputs and pseudo-codeC. Determine the relationship between components

  • How to Decompose? Decomposition can work well example: designing a restaurant menu idea: decompose by menu courses* Source, U of Toronto CS Dept But not always! example: writing a play idea: decompose by characters Goal: Find the right decomposition!

  • PseudocodePseudocode can vary from general to very detailed. It should always be descriptive enough to explain your programs approach to another programmer.

  • Example PseudocodePseudocode: Converting Fahrenheit to Celsius

    Input: A Fahrenheit valueOutput: A Celsius value

    Subtract 32 from the Fahrenheit valueMultiply the result of the previous step by 5Divide the result of the previous step by 9Print out the result

  • 21 Pickup Decomposition#1 Display Instructions

    The purpose of this component is to display instructions to the user. Pseudo-code: 1. Print out the instructions for the userInputs: NoneOutput: None

  • 21 Pickup Decomposition#2 Get Computers Move

    The purpose of this component is to decide the computers next move. Pseudo-code: 1. If 3 or fewer stones remain, then we want to pick up all remaining stones. 2. Otherwise, pick a random number between 1 and 3 3. Return the chosen valueInputs: The number of remaining rocksOutput: The number of rocks the computer wants to pick up (1-3)

  • 21 Pickup Decomposition#3 Get Users Move

    The purpose of this component is to ask the user for his/her next move. Pseudo-code: 1. Print out: Please enter # of stones to remove: 2. Get the number from the user 3. While the users # is less than 1, greater than 3 or greater than the number of remaining stones, repeat steps #1 and #2 4. Return the chosen valueInputs: The number of remaining rocksOutput: The number of rocks the human player wants to pick up (1-3)

  • 21 Pickup Decomposition#4 Run The Game

    The purpose of this component is to coordinate the entire game. Pseudo-code: 1. Print the game instructions using component #1 2. Create an initial pile of 21 stones 3. Remember that the human starts first 3. While there are stones left A. Print out the current board status B. If its the humans turn, ask component #3 for a move C. Otherwise, ask component #2 for the computers move D. Remove the specified number of stones from the pile E. If the game was won, print the outcome and stop F. Otherwise, its the other players turnInputs: NoneOutput: None

  • Top Down Design ProcessStep 3: Implement each component using one or more C++ functions

    A. If two components are very similar, consider writing a single function for both components.

    int GetComputerMove(int rocksleft){ int num_to_pickup; if (rocksleft

  • Top Down Design ProcessStep 4: Unit test each component in isolation A. Use your pseudo-code and input/output specs to identify test cases Consider boundary conditions and bad parameters! If we We Expectpass inthis Result 11 22 33 > 31
  • Top Down Design ProcessStep 5: Combine tested components into a single program

    A. If you dont have time to finish a component, just write an empty placeholder function for it (This enables you to test the parts of the program that you have finished.)...void PrintInstructions(void){ // placeholder: Ill add code here later!} void RunTheGame(void) { PrintInstructions();

    int numStones = 21, curplayer = 0; while (numStones != 0) { cout

  • Top Down Design Process

    A. Identify appropriate test casesConsider boundary conditions and bad parameters B. Test your whole program, fixing any bugs you find E. Save your test cases in case you need to retest laterStep 6: System test your entire program (or as much is completed) to ensure it works as a whole

  • Top Down Design Process

    A. Often youll write a function, like one that sorts a group of numbers, that is widely useful. B. Keep these functions handy to use in other programs C. Since theyre already tested, theyre like free code!Step 7: Identify any components that might be useful in other programs.

  • RefactoringSo youve completed your version of 21 Pickup and you have a few spare hours to wasteYou decide to improve (refactor) your computer player so it plays a better game.

  • RefactoringWe can use our updated component without having to make any changes to the rest of our program!Notice that our new component still accepts the same inputs and returns the same outputs.This is a good thing! Our smart design has isolated the impact of small changes to our program.

  • Program Decomposition ConclusionBy breaking a big problem down into smaller, more manageable components, we make it easier to solve.Identify each components inputs, output and pseudo-code.Design components such that small changes to one component dont require changes to other components.Build and test each component separately and then test them all together when youre done.Save useful components for later so you can save time.

  • Type CastingQuestion: What happens if you try to put an 8x10 photo in a 4x6 frame?Answer: You end up losing some of the information in the picture.

  • Type Castingint main(void)// example #1{double ding = 1.235;int dong;

    dong = ding;// Any problem here?}

    int main(void) // example #2{double ding;int dong = 55;

    ding = dong;// Any problem here?} Storing a floating point value into an integer155.0Integer variables can only hold whole numbers. Theyre less precise than doubles or floats (which can hold fractional numbers too).

    So when you copy a double or float value into an integer variable, the integer loses the fractional part... This can sometimes result in bugs!

  • Type CastingWhen we assign a variable of one type (e.g. int) to a variable or expression of another type (e.g. float), this is called type casting.There are two ways to deal with type casting in C++: 1. Let the compiler do it for you automatically. 2. You do it yourself with a special C++ command.We have to be careful when doing this because we may lose precision during the conversion.

  • Automatic Type CastingIts OK to set a variable of higher precision to an variable/value/expression of lower precision. (Its like putting a small picture in a bigger frame.)int main(void){ int i=1; unsigned int u=4000000000; short s=2; float f=3.5; double d=4.2;d = f;d = s; i = s; s = i;i = 3.0; i =3.0*s; u = i; i = u;

    // OK double holds more precise #s than a float// OK double holds more precise #s than a short// OK ints are a superset of shorts// BAD! shorts cant hold every possible int value// BAD! ints cant hold fractional numbers// BAD! ints cant hold fractional numbers// BAD! unsigned ints cant hold neg numbers!// BAD! ints cant hold #s larger than 2 billion

  • Explicit Type CastingIf you want to set a variable of lower precision to an expression of higher precision, you should use an explicit type cast.int main(void) // find # of peaches we can put in a bag{ floatbagVolume = 20.5; // cubic inches float peachVolume = 7; // cubic inches

    int howMany;

    howMany = bagVolume/peachVolume;

    }This tells the compiler: I meant to do that!// bad!

  • Syntax for Explicit Type Casting int main(void) // find # of peaches we can put in a bag{ floatbagVolume = 20.5; // cubic inches float peachVolume = 7; // cubic inches

    int howMany;

    }This means: Convert the expression on the right to an integer before storing it in the variable on the left.

  • Automatic Type CastingChallenge: Show how you would do explicit type casting for the each of the assignments below (if necessary).int main(void){ int i=1; unsigned int u=4000000000; short s=2; float f=3.5; double d=4.2;d = f;d = s; i = s; s = i;i = 3.0; i =3.0*s; u = i; i = u;

    // no explicit typecasting necessary! // s = static_cast(i);// i = static_cast(3.0);// i = static_cast(3.0*s);// u = static_cast(i);// i = static_cast(u);// no explicit typecasting necessary! // no explicit typecasting necessary!

  • Type Casting in Arithmetic Expressionsint main(void){doubleshhhh;

    shhhh = 5/2; cout

  • Type Casting in Arithmetic Expressionsint main(void){doubleshhhh;int a=5, b=2;

    shhhh = a/b; cout

  • Traditional C TypecastsYou may also see this alternative typecasting notation in C or C++ programs:int main(void){float f = 2.718; doubled = 3.14159;inti = -2;shorts = 32767;

    f = (float)us; // f = static_cast(us); i = (int)(f/2); // i = static_cast(f/2);s = (int)f /(int)d; // s = static_cast(f) / static_cast(d);}variable1 = (newtype) variable2;variable1 = (newtype) (expression2);