Loops: For Loops (20 xp)
Objective:
Students will practice using the FOR loop to iterate through a range of numbers, print (output) values, and
calculate a running total. This lab will focus on understanding the three core parts of the FOR loop:
initialization, condition, and iteration.
Part 1: Simple Forward Count
Create a program that asks the user for a maximum number and then uses a for loop to display every number
from 1 up to that number.
• Using a text input and getNumber(), prompt the user to enter a positive whole number that will be the
upper limit for counting.
• Create a for loop that:
o Initializes a counter at 1.
o Continues as long as the counter is less than or equal to the user's number.
o Increments the counter by 1 on each iteration.
• Using [Link](), print every number to the console inside the loop.
Example Input Example Output
Part 2: Summing All Numbers
Modify your program from Part 1 to also calculate the sum of all the numbers that were displayed.
• Before the for loop, create a variable (e.g., totalSum) and initialize it to 0.
• Inside the for loop, add the current number (your counter variable) to your totalSum variable.
• After the for loop has finished running, print a final message to the console that displays the total sum
of all the numbers.
Example Input Example Output
Challenges (Optional)
1. Challenge 1: Even Numbers with Modulus
• Modify your for loop to only display the even numbers between 1 and the user's number.
• Hint: Use the modulus operator (%) to check for divisibility by 2. If the remainder of dividing a
number by 2 is 0 (number % 2 === 0), the number is even.
2. Challenge 2: Counting by Steps
• Modify the iteration statement (the third part of the loop header) and the condition statement
so that the counter decreases by 3 in each iteration until it reaches zero.