Practice Set - Conditionals & Blocks within Braces
for CSCI E3, Harvard University author(s): Larry Bouthillier
by DustyWhite
HTML
<code style="color:maroon">Dusty White's attempt at Week 4: Assignment 1</code>
<h3>Conditionals & Blocks within Braces</h3>
<h4>2 Tasks for this Practice Set:</h4>
<ol>
<li>Use conditionals to create code which outputs a sentence to the console stating whether the variable <i>x</i> is greater to, equal to, or less than zero. It should work for any numeric value of x</li>
<li>Look at the code in this section, and fix it so that the output is correct. In your console, it should look like this (Hint: it involves braces) :
<img src="http://www.learningapi.com/cscie3/img/captains.png" title="program output" style="width:80%;padding-top:.5em;">
</li>
</ol>
JavaScript
"use strict";
// *** ASSIGNMENT 1 ***
// Insert your code for #1 here
var x = 2;
//DUSTY SEZ: Using if/else conditionals I can provide all three possibilities:
//DUSTY SEZ: (1) If variable is greater than zero do this:
if (x > 0) {
console.log(x + " is greater than zero");
}
//DUSTY SEZ: (2) *If that was not true* do this if the variable "is" zero:
else if (x == 0) {
console.log(x + " = zero");
}
//DUSTY SEZ: (3) Okay fine . . . if neither of those are true then the variable has to be "less than zero," so do this:
else {
console.log(x + " is less than zero");
}
// *** ASSIGNMENT 2 ***
// Insert your code for #2 here
var myCaptains = ["James T. Kirk", "Jean-Luc Picard", "Katherine Janeway"];
//DUSTY SEZ: A for loop is a function, so it must have a () and a { . . . } Now to get it to work took me a few days:
for (var i = 0; i < myCaptains.length; i++) {
myCaptains[i] = myCaptains[i].toUpperCase();
console.log("The Captain in Capitals is " + myCaptains[i]);
//DUSTY SEZ: THIS is the end of the function. This was giving me problems.
}
//DUSTY SEZ: THIS is not a function, so it needs to sit outside of the closing curly braces.
console.log(i + " captains have been capitalized");