CS1046 – Flipped Classroom #2 → WRITING CODE THAT USES

CS1046 – Flipped Classroom #2  WRITING CODE
THAT USES VARIABLES AND FUNCTIONS
Instructions:






You must have completed lab 3 and lab 4 and quiz 2 BEFORE doing this “flipped classroom”. Make sure
you have completed those labs and that quiz!
There are 5 exercises that must be completed to get the mark for this “flipped classroom” session
In groups of 2 or 3 students, complete the exercises. You should be pair/team programming, i.e. only
one of you needs to do the typing, but all 3 of you should be problem solving together. TAKE TURNS
DOING THE TYPING!
On completion of each exercise, have one member in your group raise his/her hand and ask the
instructor to try out your exercise. If it is completed to the instructor’s standards, move on to the next
exercise.
DO NOT DELETE ANY WORK YOU DO IN THE FLIPPED CLASSROOMS as you may need your work to
complete later exercises. For each exercise, make sure that all members in your group receive a copy of
the final product.
To troubleshoot, first discuss the issue amongst yourself. Secondly, search the internet for assistance.
Finally, if you get really stuck, ask your instructor or teaching assistant for assistance.
Objectives:




To practice deciding when you will need variables, function and arrays
To practice deciding on the names and types of the variables and arrays
To gain experience on designing functions
To learn how to collaboratively problem solve.
Exercise 1 – Practices with Variables – Calculating Odds
1. Now we are going to create a little program that tells someone their odds of winning the “Dream of a
Lifetime” home in a lottery. It should look similar to this:
http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/odds/odds/odds.gif
2. Create a folder called odds, copy the following files to it and open them in Notepad:
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/odds/odds/chances.htm
l
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/odds/odds/chances.css
3. Run the HTML program in Chrome and type in a number into the place where you enter how many
tickets you have purchased. Now try to type the word “Western” into that textbox.
4. In the HTML code, find the text box where you should type in the number of tickets you have
purchased. See if your group can figure out why it doesn’t let you type letters anymore into the box,
just numbers. Find the id for that textbox.
5. Find the id for the textbox that holds the total number of tickets sold
6. Figure out what name you should give your function that is called when the user clicks on the button.
7. Create a new .js file in Notepad and save it with the correct name (check the .html tags to see what
name the .js file should have)
8. Create 3 global variables in your .js file, one that holds the number of tickets the user has purchased,
one that holds the number of tickets sold and one that will hold your calculation for the odds of
winning.
9. Create a function that will be called when the user clicks on the button.
10. In that function, set the user tickets variable and the total tickets variable to the values entered into
the textboxes. You will need to know the ids for the 2 textboxes and you will need to use the
document.getElementById(“id”).value (use .value for textboxes) to put the textbox values into each of
the 2 global variables.
11. Using the last global variable, calculate the odds of winning as a percentage.
12. Go back to the .html file and find the <span> tag where you will output the answer and figure out
what its id is.
13. In your .js file, in the function, after you have calculated the odds of winning, add the line to put the
calculated odds global variable into the .innerHTML for that span tag. Try to concatenate a “%” sign to
the answer when you put it into the span tag.
14. Save your .js file and test it!
15. Call over the t.a./instructor once you have your program working and have him/her figure of his/her
odds of winning that lovely home!
Exercise 2 – Practices with Variables – Change Calculator
1. Now we are going to create a little program that tells a cashier how much change to give a customer.
It should look similar to this:
http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/cash/cash/cash.gif
2. Create a folder called cash, copy the following files to it and open them in Notepad:
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/cash/cash/cash.html
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/cash/cash/cash.css
3. Find the id for the textbox that holds the total bill amount and the id for the textbox that holds the
amount that the customer gave the cashier
4. Figure out what name you should give your function that is called when the user clicks on the button.
5. Create a new .js file in Notepad and save it with the correct name (check the .html tags to see what
name the .js file should have)
6. Create 3 global variables in your .js file, one that holds the total bill amount, one that holds the
amount given to the cashier and and one that will hold the amount of change that should be given
back to customer.
7. Create a function that will be called when the user clicks on the button.
8. In that function, set the total bill variable and the amount given variable to the values entered into the
textboxes. You will need to know the ids for the 2 textboxes and you will need to use the
document.getElementById(“id”).value (use .value for textboxes) to put the textbox values into each of
the 2 global variables.
9. Using the last global variable, the “change to give back” variable, calculate how much change should
be given.
10. Go back to the .html file and find the <span> tag where you will output the answer and figure out
what its id is.
11. In your .js file, in the function, after you have calculated the change, add the line to put the calculated
change global variable into the .innerHTML for that span tag, try to put a “$” in front of the amount
before you put it into the variable.
12. Save your .js file and test it!
13. Notice that it doesn’t always round the answer to 2 decimals for the cents, so it doesn’t look very nice.
You can fix this using the toFixed(numberOfRoundingDigits) method. For example, if you had:
x = 5.34275;
y=x.toFixed(2);
alert(y);
Then it would output 5.34 (it would round x to 2 digits). Try to figure out how to use toFixed() method
to make your program output an answer that looks like money rather than a bunch of digits.
14. Call over the t.a./instructor once you have your program working and have him/her figure of his/her
odds of winning that lovely home!
Exercise 3 – Practices with Variables – Height Calculator
1. Now we are going to create a little program that converts someone height from feet/inches to
centimeters OR from centimetres to feet/inches. It should look similar to this:
http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/height/height/height.gif
2. Create a folder called height, copy the following files to it and open them in Notepad:
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/height/height/height.ht
ml
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/height/height/height.css
3. Open the .html file in Chrome and notice there are two buttons  one that does the conversion one
way and one that does the conversion the other way.
4. Figure out what names you should give your functions that are called when the user clicks on the first
button and when the user clicks on the second button.
5. Create a new .js file in Notepad and save it with the correct name (check the .html tags to see what
name the .js file should have)
6. Create 3 global variables in your .js file, one called feet, one called inches and one called centi.
7. Create the two required functions (check the .html files to see what name to give each function by
looking for the onclick code)
8. Go back to the .html code and look at the <body> tag. Notice that is now:
<body onload="setUp()">
9. In your .js file, create a function called setUp. This function will be called when the page loads. It will
hide the answer area UNTIL we calculate the conversion and then unhide it. For this, all you need is
one line of code  in the setUp function, put the line:
document.getElementById("answer").hidden=true;
That line will hide from view the <h1 id=”answer”> heading area at the bottom of the webpage.
10. Save your .js file and reload your .html file in Chrome and make sure that the text:
Your converted height is:
is now hidden on the webpage.
11. In the function that converts from feet/inches to centimetres , set the feet variable equal to the .value
of the feet textbox and set the inches variable equal to the inches textbox.
12. Set the centi variable equal to the conversion (there are 12 inches in a foot, so calculate the number of
inches in total (feet*12 + inches) and then figure out the centimeters. There are 2.54 centimetres in an
inch).
13. Convert your answer to integer by using parseInt. For example:
myAnswer = parseInt(44.2222);
would put the integer 44 into myAnswer;
14. NOTE, you might need to convert the text (strings) in the text box to numbers by multiplying them by
1 (or using inches = Number(inches))
15. Go back to your .html code and find the id for the <span> tag that holds the answer
16. Go back to your .js code and right after you calculate centi, put centi into the span tag as follows:
document.getElementById(“newHeight”).innerHTML = centi;
17. Now that we have calculated the answer and put into the document area, we need to unhide it. COPY
(not MOVE but COPY) the line inside your setUp() function and paste it right below the line in the step
above, but you will need to change it slightly. Have your group figure out how to change it.
18. Save your .js file and test your first conversion button. NOTE: if you are getting the wrong answer:
you might need to convert the text (strings) in the text box to numbers by multiplying them by 1 (or
using something like inches = Number(inches))
19. See if your group can write the code to convert from centimetres to feet/inches, here are some hints:
a. Convert all the centimeters to inches first by multiplying it by 0.393
b. Convert your new answer in inches to integer by using parseInt. For example:
inches=parseInt(inches);
c. Then convert the inches to feet AND remaining inches by taking your inches and dividing them by
12 to get the feet using the / symbol for division and then MODING (modulus, remainder) to get
the inches using the % symbol for modulus (e.g. 23 inches divided by 12 would be 2 feet. 23 % 12
would be 11 inches, so 23 inches would be 2 feet, 11 inches). Use the feet variable to hold the
number of feet and the inches variable to hold the remainder for the inches.
d. You might need to use the .toFixed() or Math.floor() to get rid of decimals.
20. After you have done your calculations put something like this to output the answer:
document.getElementById(“newHeight”).innerHTML = feet + “ feet and “ + inches “ inches.”;
21. Remember to unhide the answer again
22. Call over the t.a./instructor once you have your program working go metric on their height!
Exercise 4 – Practices with Arrays – Dream Home
1. Now we are going to create a kind of “Russian Roulette For Homes” program allows a user to spin
(click on a button) and play for a randomly drawn house (from at least 4 houses) but one house will be
a crappy house. If your group wants, you could do this game instead for a randomly drawn car, or
horse, or whatever images you would like. When you are finished, it should look similar to this:
http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/dream/dream.gif
2. Create a folder called dream, copy the following files to it and open them in Notepad:
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/dream/dream.html
 http://www.csd.uwo.ca/~lreid/cs1046/flippedclassroom/FlippedTwo/dream/dream.css
3. Open the .html file in Chrome and notice there is one button that the user clicks on to see which
randomly drawn house he/she will be playing for.
4. Look at the html tags in the .html file and figure out what name to give the function AND the id for
the <img> tag.
5. Create a new .js file in Notepad and save it with the correct name (check the .html tags to see what
name the .js file should have)
6. In your .js file, at the top of the file, create a global variable called homesNum and a global variable
called homeSpun
7. Create a global array called homes and initialize to the image URL of at least 4 homes (make one home
be a dump) your group finds on the internet. The line of code should look like this (except with the urls
that you found):
var homes = [“http://a.com/a.jpg”, “http://a.com/b.jpg”, …];
NOTE: if you want, you can do cars, or airplanes, or …
8. Create a function with the name that matches the onclick name in the .html file for the “SPIN TO WIN”
button. Inside the function:
a. Set the variable homesNum equal to random number between 0 and the length of your homes
array.
b. Set the variable homeSpun equal to the array homes at the random index in homesNum
c. Add the following line to set the <img> tag with the id of “whichOne” to be the src attribute for
the <img> tag to be the URL for the randomly selected home:
document.getElementById(“whichOne”).setAttribute(“src”,homeSpun);
9. Save your .js file and reload your .html file into Chrome and make sure it works.
10. Now create a global variable called colNum, a variable called colSpun and a global array called backCol
and fill the backCol with some (at least 3) of the colour names found here (put the colour names in
quotes when you put them in the array): http://www.w3schools.com/colors/colors_names.asp
11. Go back to the function you just finished and add the line to set the colNum variable to a random
number between 0 and the number of colours in the backCol array
12. Figure out how to set colSpun equal to the color in the backCol array at the index value randomly
generated in colNum
13. Add this line to change the background colour of the webpage randomly also when the user clicks on
the button:
document.body.style.backgroundColor = colSpun;
14. Call over the t.a./instructor once you have your program working to see if the instruction can win the
“Home of her dreams” or the “Home of her nightmares”!
Exercise 5 – Continuing on with the “Guess A Number” game
1. Have one person in your group create a new folder for all your work today. Then open a text editor such
as Notepad and load your work from your first exercise in flipped classroom 1 OR get a copy of last week’s
completed exercises from here:
a. Guess A Number HTML file
b. Guess A Number CSS file
2. Save the above files into your new folder.
3. Add the code to your .html file to include an external JavaScript file (a .js file), give it any descriptive name
you wish.
4. Create a new JavaScript file (.js) in Notepad in
the same folder as above and give it the same
file name as in the step above.
5. Decide how many and which variables you
would need to complete this game. For
example, you are probably going to need a
variable to hold the user’s guess, so you need
one variable called userGuess. For this
program we will use all global variables so
they will all be declared them all at the top of
the .js file.
6. Declare all the variables you think you will
need near the top of your JavaScript file. Give them good descriptive variable names (you will be marked
on your variable names in your individual assignments).
NOTE: Remember, if your group is planning to keep track of the number of guesses the user is taking, you
will need a variable for that also. For example, if your program is only going to give the user 3 chances to
guess the number, then you will need a variable to hold how many guesses the user has made so far.
7. This game requires the program to:
a. Generating a random number to be the answer
b. Get (set the guess variable equal to what’s in the textbox) a guess from the user after he/she clicks
on the button
c. Check the guess against the answer and output if it was too high, too low or just right.
NOTE: THINK of each of those above 3 steps as tasks (aka functions), and do create 3 function headers
(the first line and the opening and closing brackets and the opening and curly braces) for each of the
tasks listed above. Pick good descriptive function names for each function, type the header (first line
with function name and brackets) and put a
comment line in the middle as a placeholder,
function setTheAnswer () {
eventually this spot will be where you add the
//code goes here
code. For example, you might have something
}
like this 
8. As of right now, if you finished labs 3 and 4, you should be able to write the code to complete 2 of the 3
tasks (aka functions) above. Figure out which 2 tasks you can complete and then write the code for them.
REMEMBER TO PROPERTLY INDENT YOUR CODE!
9. In both of the 2 tasks/function you have completed, put an alert box at the end of it that displays the
variable you just set, so that you can see if your function is working.
TESTING YOUR CODE:
10. In the .html file, change the <body> tag to be: <body onload=” setTheAnswer()”>. Where setTheAnswer
is the name of the function you created above that puts the random number between 1 and 100 into the
answer variable. This will call that function whenever the page is reloaded or refreshed and thus
immediately set the answer to a random number between 1 and 100 that we are trying to get the user to
guess before the user even gets a chance to press the button to guess (which is what we want).
11. Now change the .html file so that when the user clicks on the button, it calls your function that sets the
variable holding the user’s guess to be whatever is in the textbox. We want to see if your function is
correctly setting the guess variable.
12. Call over the t.a./instructor to check what you have done so far.
Remember:
 Have only ONE member in your group:
 Log into OWL
 Find the Flipped Classroom Two Assignment in the Assignments section
 In the assignment submission text box, type the first names of all group members who were
participating in today’s Flipped Classroom. DO NOT include the names of any group member who did
not come to class today.
 Upload all the files you created today to OWL in the assignment called Flipped Classroom Two.
 Hit submit.
NOTE: at this point, all the members in your group should now be able to see all the files you submitted
 Make sure that the instructor has recorded your name and Western user ID so that you get the marks for
participating in this flipped classroom!