for
Practice¶Construct for
loops that accomplish the following tasks:
1for (let i = 0; i <= 20; i++) {
2 console.log(i);
3}
1for (let i = 12; i >= -14; i-=2) {
2 console.log(i);
3}
Initialize two variables to hold the string 'LaunchCode'
and the array
[1, 5, 'LC101', 'blue', 42]
, then construct for
loops to accomplish
the following tasks:
1let str = 'LaunchCode';
2let arr = [1, 5, 'LC101', 'blue', 42];
1for (let i = 0; i < arr.length; i++) {
2 console.log(arr[i]);
3}
Construct a for
loop that sorts the array
[2, 3, 13, 18, -5, 38, -10, 11, 0, 104]
into two new arrays:
evens
array to hold the even numbers and an odds
array for the odd numbers.1let otherArr = [2, 3, 13, 18, -5, 38, -10, 11, 0, 104];
2let evens = [], odds = [];
evens
first. Example:
console.log(evens);
1console.log(evens);
2console.log(odds);
while
Practice¶Define three variables for the LaunchCode shuttle---one for the starting fuel level, another for the number of astronauts aboard, and the third for the altitude the shuttle reaches.
Construct while
loops to do the following:
1const input = require('readline-sync');
2let fuelLevel = 0, numAstronauts = 0, altitude = 0;
3
4while (fuelLevel <= 5000 || fuelLevel > 30000 || isNaN(fuelLevel)) {
5 fuelLevel = input.question("Enter the starting fuel level: ");
6}
1while (fuelLevel-100*numAstronauts >= 0) {
2 altitude += 50;
3 fuelLevel -= 100*numAstronauts;
4}
After the loops complete, output the result with the phrase, The shuttle
gained an altitude of ___ km.
1let output = `The shuttle gained an altitude of ${altitude} km.`;
2
3if (altitude >= 2000) {
4 output += " Orbit achieved!";
5}