Iteration Homework
An intro to data abstraction
Homework Assignment: for Loop Challenge
Task: Create a program that does the following:
Initialize an array with the names of five of your favorite movies. Use a for loop to iterate through the array and print each movie name to the console. After printing all movie names, print a message indicating how many movies you listed.
%%js
let movies = ["Spiderman","Jumanji","Deadpool","Avengers","Spongebob"]
for(let i = 0; i <= movies.length -1;i++){
console.log(movies[i])
}
console.log("Total Movies: ", movies.length)
<IPython.core.display.Javascript object>
Homework
Create a 3 by 3, 2D list that represents a tictactoe board. Use “X” for X, “O” for O, and None for empty tiles.
Ex. board = [[“X”,”None”,”O”],
[“X”,”O”,”None”],
[“O”,”None”,”X”]]
Iterate over the board and identify whether it is player X’s or player O’s turn.
Hint: count the number of moves(non-None). (X goes first)
Optional: use console.error() to report an error if the board is illegal (ex. 7 “X”s and 2 “O”s)
%%js
let board =[//must be capital
["X","","O"],
["X","O",""],
["O","","X"]
]
let totalMoves = 9
let turn = null // flase is X true is O
let totalNumberX = 0
let totalNumberO = 0
for(let rowArray of board){
for(let i = 0; i < rowArray.length; i++){
let mark = rowArray[i]
if (mark === "X"){
totalNumberX++
console.log("Is X")
}else if(mark === "O"){
totalNumberO++
console.log("Is O")
}else if(mark === ""){
console.log("Is empty")
}
}
}
// X will go first so in a tie its X`s turn
console.log(totalNumberO)
console.log(totalNumberX)
function determainTurn(){
if(totalNumberO > totalNumberX || totalNumberO == totalNumberX ){
console.log("Its X`s turn")
} else{
if (totalNumberO < totalNumberX){
console.log("Its O`s Turn")
}
}
}
determainTurn()
<IPython.core.display.Javascript object>
H.W application of While Loops.
Create the Outer Loop:
Use a while loop that runs while outerFactor is less than or equal to 10. Initialize the Inner Loop Variable:
Inside the outer loop, create another variable called innerFactor and set it to 1. Create the Inner Loop:
Inside the outer loop, use another while loop that runs while innerFactor is less than or equal to 10. Calculate the Product:
Inside the inner loop, calculate the product of outerFactor and innerFactor. Print the Product:
Print the product using console.log(), formatting the output neatly. Increment the Inner Loop Variable:
After printing the product, increment innerFactor by 1. Move to the Next Line:
After the inner loop finishes, print a new line to separate rows. Increment the Outer Loop Variable:
Increment outerFactor by 1 to move to the next row in the table.
%%js
let i = 0
while(i < 10){
let ii = 0
i++
while(ii < 10){
ii++
console.log(ii * i)
}
}
<IPython.core.display.Javascript object>