Session_2_Student_Instructions.pdf

Embed Size (px)

Citation preview

  • 8/9/2019 Session_2_Student_Instructions.pdf

    1/8

    Computer Science Programming SOFT10101

    Session 2 Selection using if and repeating using for

    Outcome of session Further work on declaring and using basic variables Using if/else to control actions in the program User input of data Random number function and modulus operator Using loops to do things repeatedly Using the debugger to step through a running program

    If during the following steps you cannot follow something, or it doesn't work, please checkwith your neighbour that you are doing it right. If it still doesn't work, raise your hand andthe tutor will try to help.

    NOTE! There will be a dropbox on NOW called Week2. You are EXPECTED to code for 8-10 hours per week outside class.So put your programs in the dropbox (just the cpp files, not the whole folder) so that thereis evidence of your activity BEYOND the lab.

    Starting Up1. Create a local subfolder ie NOT in your shared drive, but on the desktop

    (Remember at the end to save the .cpp files back either to the dropbox on NOWor save the whole project to your drive).

    SYNTAX (as covered in lecture) if/else example:

    if (x==1){

    cout

  • 8/9/2019 Session_2_Student_Instructions.pdf

    2/8

    VERIFY that the program compiles and builds and, when ctrl-F5 is entered, displaysToo low.

    Change the value of aInt to 200 by an ASSIGNMENT statement just before the if. (Remember to put a semicolon at the end.)

    TEST to v erify that the changed program now display Too High when run.

    Look up the use of else if to allow more choices. (Google is your friend) Change the code to use else if so that it displays Too Low if aInt is below 10, Perfect ifaInt is EQUAL to 10, and Too High otherwise. (Recall from the lecture how we test forequality.)TEST by changing the assignment statement to ensure that Perfect will be displayed ifaInt is 10.

    Part BUse Edit|Advanced|Comment Selection (or the ctrl shortcuts) to comment out all the codeyou have just added.

    Now we will add a new section to check that it also works when applied to a floating pointvariable ie bFloat.What do you think will happen if you add the following code?if (bFloat==3.6){

    cout

  • 8/9/2019 Session_2_Student_Instructions.pdf

    3/8

    This shows that your program is at this point, waiting to execute the line.

    Look at the bottom left window. Should show current values of variable ie bFloat.

    9. Does it have the value you expect? Is it a value of 3.6 or something else? 10. Hover mouse above the variable name anywhere in your program.

    It will show you current value ie the values they have just before executing the line wherethe breakpoint is. (So if the line is an assignment, the breakpoint occurs BEFORE thevalue has changed.)

    Get program to step to the next line:

    12. Select Debug|Stepover.13. Does the yellow marker get to the Hooray line?

    Using the debugger like this will allow you to see the decisions made by your code as aresult of the tests (if statements) you have set up. Sometimes this can be quite a surprise!If it doesn't do the things you expect, stop debugging, and start again, setting up multiplebreakpoints and examining the values of the variables, then seeing whether the way youwrote the if statement makes sense.

    Part D Multiple conditions An if can be dependent on multiple conditions connected by && (denoting AND) or ||(denoting OR).NOTE each condition has to be able to be evaluated as true or false on its own.In maths, we can say:

    5

  • 8/9/2019 Session_2_Student_Instructions.pdf

    4/8

    Katch-McArdle formula and then set a few values so that you can use if and else if todisplay different messages about it.

    Part A Now change your code from that week so that: For a BMI of less than 12, it displays a message to say Underweight

    For a BMI if greater than 25, it displays a message to say Overweight For a BMI between these two limits, it displays a message to say Practically

    perfec t

    NOTE you must do this with a SINGLE if, else if, else sequence.

    Part B user inputWe have used coutheight; //this takes what the user types and stores it in the variable called height

    We probably ought to output something first to the user, to tell them what we want them todo. This is called a PROMPT:

    coutheight; // they enter a sensible value (!)

    Get the user to enter the height and weight and store them in the variables.

    Then use them to calculate the BMI CHECK that the program displays the expected response (you can use thedebugger to check the BMI value)

    (NOTE what TYPE have we given height? Do we care? WHY?)

    SYNTAX the while loopwhile (condition){

    // DoSomething lines of code here}

    For example:int answer =1; //start valuewhile (answer ==1) //end condition{

    //Prompt and get height and weight// Do the BMI calculation//Use if to display an appropriate response//Prompt and get a value for answer (do they want to try again? 1 for yes, 0 for no)

    }

    The while loop repeats as long as the condition is true. We frequently use a setup wherewe increment a COUNTER inside the loop, and the while (condition) depends on the valueof the counter eg:

  • 8/9/2019 Session_2_Student_Instructions.pdf

    5/8

    int myvalue =1; //start valuewhile (myvalue

  • 8/9/2019 Session_2_Student_Instructions.pdf

    6/8

    that value into an integer variable for each player called Player1 and Player2. (So youneed to write a prompt for the first player, then read in his/her choice, then prompt thesecond player, and read in his/her choice. You need to clear the screen between theplayers so the second doesnt see what the first typed in ).

    Then you need to use 'if statements' to check all the cases eg where Scissors beats

    Paper, Paper beats Stone, and Stone beats Scissors, and display an indication of whetherPlayer1 or Player2 won, or whether they tied. So if Player 1 entered 1 (representingscissors), and Player 2 entered 2 (representing paper), your program would show "Player1 won!" or something similar.

    Modify this program so that it repeats the game until the user decides to stop (while loop).

    Followup work

    Step 1

    The 'if statements' for establishing who won and lost are fairly tedious to write. Becausewe are using numbers to represent the 3 possibilities, we can subtract the valuesrepresenting the choices and use the result to simply the decision making. So for exampleif Player1-Player2 is zero, we have a tie, whereas if Player1-Player2 is -1, Player 1 haswon. (These are obviously not the only possibilities.)

    Look up the switch statement. Use different cases for the value of Player1-Player2 tomake decisions as to which response to display. Write yourself a TEST PLAN to verify thatyou catch all the cases (ie a list of all the possible values of this variable and the expectedresult).

    Step 2

    Instead of having 2 players entering their choices, you can get the program to play againstyou.

    Replace the portion of the program where you prompt the second player and take in theirchoice, and instead use a random number generator to make the program choice. Look upthe function rand() . To include it in the program you need to add a new directive at the topof the program. After #include "stdafx.h" add the line:

    #include "math.h"

    Then you need to limit the range of random numbers so that the choice is 1, 2 or 3. Thereare a few ways of doing this. The simplest is to use the MODULUS operator expressedby the % sign. This is like a division, but instead returns the remainder from an integerdivision. If I have a line of code saying:

    x = y%3;

    then, for example, if y is 0, x takes the value 0; if y is 10, x takes the value 1 (y/3 has aremainder of 1); if y is 14, x takes the value 2 (y/3 has a remainder of 2).

    Further exercises to do AT HOME

  • 8/9/2019 Session_2_Student_Instructions.pdf

    7/8

    DESIGN (plan) programs (and then implement them) using loops to do the following:

    Program 1Generates a countdown from 10 till 0, with a timed pause between each line, that endsThunderbirds are go!. To get the delay y ou can call the function :

    Sleep(NNN); //NNN is time in milliseconds

    To get access to this function, you need to add the extra directive at the top of theprogram:

    #include

    Program 2 A program that converts from ounces to grams two versions one that gets the user toenter the number of ounces and then displays it in grams eg 3.5 ounces =>99.2 grams

    The other displays a conversion table for 1 till 10 ounces into grams.

    Program 3Prompt the user to enter the currency conversion rate for pounds per dollar (eg 0.7 poundsper dollar).Then display a table showingDollar Pound1 0.72 1.4Etc.

    Read up about break ;Use it (or another method) to ensure the table displays only as far as 10 pounds (notdollars thats easy).

    You can include one loop INSIDE another:Program 4

    A program that prompts the user for an integer.When they enter a positive integer eg 7, it then displays the 7 times table (up to 10 times

    7), then prompts for a new integer.It repeatedly displays times tables (as specified by user input) until they enter 0 instead ofa positive integer.So it has NESTED loops:

    Loop until user enters 0Prompt and get user number NDisplay heading Times table for N (where N is the number they enter) Loop over range of times table (1 till 10)

    Display index and index * N

    You can include one loop AFTER another:Program 5

  • 8/9/2019 Session_2_Student_Instructions.pdf

    8/8

    A program that prompts the user for their age, takes it in, and works out their age in 10,20,30,40,50 years time.The program must repeatedly prompt and take in the age until they enter an age that is inthe range of 18 to 40.So there are 2 consecutive loops:

    Loop until age is in correct range (while loop)Prompt and get the ageCheck age against valid limits

    Loop over future years 10-50 in increments of 10 (for loop)Display age and each future date

    Program 6Update your earlier lab program to instead play the Big Bang Theory game of Rock-paper-scissors-lizard-Spock. In this case it could generate LOADS of if/else code. Be a LAZYCODER and try to find a way of making it data driven.

    REMEMBERWe expect to see EVIDENCE in the dropbox that you are working outside of lab If youwant feedback on your work, then please show it to your tutor during the next lab.