Exercise Solutions: Loops

for Practice

  1. Construct for loops that accomplish the following tasks:

    1. Print the numbers 0 - 20, one number per line.
    1for (let i = 0; i <= 20; i++) {
    2   console.log(i);
    3}
    
    1. Print the EVEN numbers 12 down to -14 in descending order, one number per line.
    1for (let i = 12; i >= -14; i-=2) {
    2   console.log(i);
    3}
    
  2. 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];
    
    1. Print each element of the array to a new line.
    1for (let i = 0; i < arr.length; i++) {
    2   console.log(arr[i]);
    3}
    
  3. Construct a for loop that sorts the array [2, 3, 13, 18, -5, 38, -10, 11, 0, 104] into two new arrays:

    1. Define an empty 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 = [];
    
    1. Print the arrays to confirm the results. Print evens first. Example: console.log(evens);
    1console.log(evens);
    2console.log(odds);
    

Back to the exercises.

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.

  1. Construct while loops to do the following:

    1. Prompt the user to enter the starting fuel level. The loop should continue until the user enters a positive value greater than 5000 but less than 30000.
    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}
    
    1. Use a final loop to monitor the fuel status and the altitude of the shuttle. Each iteration, decrease the fuel level by 100 units for each astronaut aboard. Also, increase the altitude by 50 kilometers. (Hint: The loop should end when there is not enough fuel to boost the crew another 50 km, so the fuel level might not reach 0).
    1while (fuelLevel-100*numAstronauts >= 0) {
    2  altitude += 50;
    3  fuelLevel -= 100*numAstronauts;
    4}
    
  2. After the loops complete, output the result with the phrase, The shuttle gained an altitude of ___ km.

    1. If the altitude is 2000 km or higher, add "Orbit achieved!"
    1let output = `The shuttle gained an altitude of ${altitude} km.`;
    2
    3if (altitude >= 2000) {
    4  output += " Orbit achieved!";
    5}
    

Back to the exercises.