Skip to the content.

Iterations Popcorn Hacks

My finished iterations popcorn hacks!

Popcorn Hacks on Iterations in JavaScript

Instructions:
Complete the exercises below in JavaScript.
You can run and test your code in a JavaScript environment.

Exercise 1: Counting with a For Loop

Write a JavaScript for loop that prints all numbers from 1 to 10.
Example:
Output:
1
2
3
9
10
%%js
let a=1;//declares the first number
for (let i=0; i<10; i++){//repeats 10 times 
    console.log(a);//prints a
    a+=1;//adds one to a
}
<IPython.core.display.Javascript object>

Exercise 2: Sum of Numbers

Write a for loop in JavaScript to calculate the sum of all numbers from 1 to n using a loop.
Example:
Input: 5
Output: 15 (because 1 + 2 + 3 + 4 + 5 = 15)
%%js
let n=10;//makes n, which will be used to figure out what number the code sums up to
let a=n; //makes a the same value as n
for (let m=n; m>1; m--){ //repeats n times
    n-=1; //subtracts one from n 
    a= a+n; // adds n to a
}
console.log(a);//prints the total sum

Exercise 3: Looping through Arrays

Write a JavaScript program to iterate through an array of names and print each name.
%%js
const names = ['Ditto', 'Vaporeon', 'Articuno', 'Snom'];//names of the people (or in this case, pokemon...) 

for (let name of names){//counts the amount of names using name of
    console.log(name);//prints the amount of names
}

<IPython.core.display.Javascript object>