Skip to content
ExamSpine

Lesson 3.6

Loop bounds from input; a running total over a range

Part 3: RepetitionReading, about 5 min2 exercises in this lesson

Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.

Loop bounds from input

By the end of this you will be able to use numbers the user types as the start and end of a for loop, include the end on purpose, keep a running total across the loop, and put values on one line with a separator between them.

The numbers in a for line do not have to be written into the program. They can be variables that hold numbers the user typed. The program then decides how many turns to take while it runs, but still before the loop starts, so for is still the right loop.

A count from input

A shop till first reads how many items there are, then reads each price and adds it to a total.

count = int(input())
total = 0
for i in range(count):
    price = int(input())
    total = total + price
print("Total: " + str(total))
import java.util.Scanner;

public static void main(String[] args) {
    Scanner scanner
        = new Scanner(System.in);
    int count = Integer.parseInt(
        scanner.nextLine());
    int total = 0;
    for (int i = 0; i < count; i++) {
        int price = Integer.parseInt(
            scanner.nextLine());
        total = total + price;
    }
    System.out.println("Total: " + total);
}

If the user types 3, then 4, 10 and 6, it prints Total: 20. The running total works just as it did with a while loop: it starts at 0, and each turn adds the value of that turn. The counter i is not used inside the body. The loop is there only to run once per price.

If the count is 0, the body never runs. In Python, range(0) gives no numbers. In Java, 0 < 0 is false at the first check. Either way the program prints Total: 0, which is right: no items cost nothing.

Both ends from input

Now a reader wants to print pages, from a first page to a last page, both typed in. This program lists them on one line, with a comma and a space between them.

first = int(input())
last = int(input())
line = ""
for page in range(first, last + 1):
    if page > first:
        line = line + ", "
    line = line + str(page)
print("Pages: " + line)
import java.util.Scanner;

public static void main(String[] args) {
    Scanner scanner
        = new Scanner(System.in);
    int first = Integer.parseInt(
        scanner.nextLine());
    int last = Integer.parseInt(
        scanner.nextLine());
    String line = "";
    for (int page = first;
            page <= last; page++) {
        if (page > first) {
            line = line + ", ";
        }
        line = line + page;
    }
    System.out.println("Pages: " + line);
}

The counter here is called page, not i. Any name works, and a name that says what the counter stands for makes the loop easier to read.

The last page must be printed too. In Python, range leaves out its end, so the end is written one past the last page: last + 1. In Java, the condition page <= last keeps going up to and including the last page.

Here is a trace when the user types 3 and 6.

TurnpageIs page > first?The line at the end of the turn
13No3
24Yes3, 4
35Yes3, 4, 5
46Yes3, 4, 5, 6

It prints Pages: 3, 4, 5, 6. From 3 to 6 is four pages, not three: when both ends count, the number of values is last - first + 1.

A separator between values

Four pages need only three separators, one between each pair. So the loop adds a separator before every page except the first, which is the page where page > first is false. Adding ", " after every page instead would leave an extra one at the end of the line, after the 6.

Two common slips

  • Leaving out the end. range(first, last) in Python, or page < last in Java, stops one page early.
  • One separator too many. Count the gaps: a row of one or more values needs one separator fewer than it has values.

Now try it yourself on the questions below.

Exercise 3.6.13.6.1 · Write itSum a range

Write a program that reads two whole numbers, a start and an end, and prints the sum of every number from the start to the end, inclusive.

  1. Read the start on the first line and the end on the second line.
  2. Add every number from the start to the end, including both.
  3. Print Sum: followed by the total.

The start is always less than or equal to the end. Both are whole numbers from 1 to 1000. Your program is run several times. Only what it prints is checked.

In Python, remember that the end value of range is excluded, so to include the end, go one past it.

Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.

Examples

Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.

  • 1 + 2 + 3 + 4 + 5 = 15 (rule 2)

    You type

    1. typed: 1
    2. typed: 5

    It prints

    Sum: 15
  • start equals end, sum is just that number (rule 2)

    You type

    1. typed: 3
    2. typed: 3

    It prints

    Sum: 3
  • 2 + 3 + 4 = 9 (rule 2)

    You type

    1. typed: 2
    2. typed: 4

    It prints

    Sum: 9
solution.pySolution.java

Exercise 3.6.23.6.2 · Write itTimes table row

Write a program that reads a number and prints its times table from 1 to 10, all on one line separated by spaces.

  1. Read one number on a single line.
  2. Print the products n * 1, n * 2, ..., n * 10 on a single line.
  3. Separate the products with exactly one space.

The number is always a whole number from 1 to 1000. Your program is run several times. Only what it prints is checked.

Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.

Examples

Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.

  • the 3 times table (rule 2)

    You type

    1. typed: 3

    It prints

    3 6 9 12 15 18 21 24 27 30
  • the 1 times table (rule 2)

    You type

    1. typed: 1

    It prints

    1 2 3 4 5 6 7 8 9 10
  • the 5 times table (rule 2)

    You type

    1. typed: 5

    It prints

    5 10 15 20 25 30 35 40 45 50
solution.pySolution.java