Step 7

Creating the spamWord2 function


Next, add the code underneath the “spamWord” function to create the new “spamWord2” function.

This function will also spam words a given number of times; however, it will spam them all on the same line. The previous function would spam one word per line, we’ll see this in action when we test them both.

Just like the previous function, this one will need two parameters to do its job, the same ones too!

The for loop


Next, add the code inside the “spamWord2” function as shown. For this function we use another new programming tool called the for loop.

The for loop works the same as the while loop except for one main difference. It has all of its important information on one line!

Next to the word for, we see that we create the variable “x” just like before. Next to it we have the condition that uses that variable and makes the loop stop. Lastly, we have something that modifies the variable “x”, the “x++” that we saw earlier.

This is the format of the for loop. The variable used in the loop, the condition used to stop the loop, and some modification to the variable, all listed in the same line. Programmers like using this loop because it helps keep all the information in one place. Both loops have their pros/cons, it will take time and practice using them to learn all of them.

Inside the for loop we again print out the string. However, we use “printf” this time instead of “println”, this makes it so the string we print doesn’t make a new line. (That’s what the “ln” stands for)

Lastly, outside of the loop, we have another printf with “%n” inside it. This is how you manually make a new line, like pressing the “Enter” key on a keyboard.