asked 18.5k views
3 votes
Write a for loop that prints: 1 2 … lastnumber ex: if the input is: 4 the output is: 1 2 3 4

asked
User Wf Khani
by
8.1k points

1 Answer

3 votes

Final answer:

A for loop to print numbers from 1 to a given last number (inclusive) can be written using a range function in Python. The loop starts at 1 and iterates through to lastnumber, printing each number separated by a space.

Step-by-step explanation:

To write a for loop in a programming language like Python that prints numbers from 1 to lastnumber, you'll need to ensure that the loop starts at 1 and ends at lastnumber (inclusive). Here is an example of how you can write such a for loop:

lastnumber = 4 # This is the input
for i in range(1, lastnumber + 1): # Starts at 1 and goes up to and including lastnumber
print(i, end=' ') # Prints each number followed by a space instead of a new line

This code will produce the following output for the input 4:

1 2 3 4

The range function is used to generate a sequence of numbers, which the for loop then iterates through. By using lastnumber + 1, you make sure the for loop includes the last number in its output.

answered
User Bkwdesign
by
8.6k points