Recall: You can put if-statements inside other if-statements (infinitely)... that's called "nesting".
if (something == true) {
if (some_other_thing == true) {
if (x % 2 == 0) {
// Code here
}
}
}
We can "nest" a loop inside another (as many times as we need) just like the if-statements.
for (let outter_loop = 0; outter_loop < 10; outter_loop++) {
// Maybe some code here
for (let inner_loop = 9; inner_loop > 0; inner_loop--) {
// Code goes here
}
// Maybe other code here
}
They can be different types of loops, too! We can nest as many as we need to. Sometimes nesting three or four deep is necessary.
let output = "";
for (let x = 1; x < 8; x++) {
let y = x;
while (y > 0) {
output += "*";
y--;
}
console.log(output);
}
The absolute best way to learn this is through trying it. At this point you should know the syntax of loops and the reasons for using them. If you are at all confused, you probably missed the previous lessons on While, Do While, and For. YouTube has fantastic examples and tutorials.
Create a new coding file for yourself, preferably in your Unit 3 folder, named 3.5 - Nested Loops.js
.
Note - these will require prompt()
:
npm install prompt-sync
const prompt = require("prompt-sync")();
Emoji's might not work in your console. It seems to depend on the computer. If emoji's aren't working, you can use one of the characters from this website for the tasks below...
-
print_line()
- You will repeatedly ask the user how many emoji's (or interesting characters) to print on one line:- Ask the user to enter a number.
- Print a line of emojis (of your choice) the length the user asked.
- Then ask them again.
- If they enter a negative number, the program quits.
We will assume they are always entering a number.
➡ Emoji's can be found here
➡ Fun ASCII characters can be found hereJust copy and paste into quotations "💩":
console.log("☣")
How many should I print? 5 ☣☣☣☣☣ How many should I print? 10 ☣☣☣☣☣☣☣☣☣☣ How many should I print? -3 Bye!
💥 Want to take it to the next level? Give a menu so the user selects an emoji from a list and then ask them how many to print.
print_square()
- Very similar to #1 above, but this time you need to output a square of emoji's.
For Example:How big is the square? 5 ⚽⚽⚽⚽⚽ ⚽⚽⚽⚽⚽ ⚽⚽⚽⚽⚽ ⚽⚽⚽⚽⚽ ⚽⚽⚽⚽⚽ How big is the square? 3 ⚽⚽⚽ ⚽⚽⚽ ⚽⚽⚽ How big is the square? -1 Bye!
💥 Want to take it to the next next level? Print an outlined square with a different emoji in the middle print_outline()
:
⚽⚽⚽⚽⚽
⚽🏈🏈🏈⚽
⚽🏈🏈🏈⚽
⚽🏈🏈🏈⚽
⚽⚽⚽⚽⚽
How wide is the diamond? 5
⚽
⚽⚽
⚽⚽⚽
⚽⚽⚽⚽
⚽⚽⚽⚽⚽
⚽⚽⚽⚽
⚽⚽⚽
⚽⚽
⚽
🐿️