Building a Complete Java Program

Structured Program Composition means combining small, understandable operations into a program whose execution you can follow. In Java, a method can calculate one contribution, a conditional can choose that contribution, and a loop can combine many contributions. Your task is to connect these pieces so that the complete program carries out its stated rule, including at boundaries such as the first and last repetitions.

Connect the building blocks

A program's control flow is the order in which its statements execute. Read that order from the active method, rather than simply reading the file from top to bottom. A helper method's declaration describes work that becomes active when the program calls it.


Structure

Role in the complete program

Placement question

Sequence

Performs operations in order

What must happen before the next operation?

Conditional

Chooses a branch using a true or false condition

Does this decision concern one item or the completed result?

Loop

Repeats a block while its condition permits

What work belongs to every repetition?

Method call

Runs a named operation and resumes the caller

How will the caller use the returned result?


For example, a decision about one round's points belongs in the calculation for that round. A decision about the total points belongs after the total has been completed. Braces make these relationships explicit; indentation helps you see them.



Keep repeated work inside the loop

A variable that stores a running total is an accumulator. For additive contributions, its governing update is:


new total=old total+returned contribution\text{new total} = \text{old total} + \text{returned contribution}


Initialize the total once before repetition. Add each contribution inside the loop. Use the completed total after the loop. If you reset the total inside the repeated block, earlier contributions disappear.


An iteration includes the work in the loop body. In a basic for loop, initialization happens once, the condition is checked before each iteration, and the update runs after each normally completed iteration. A while loop also checks its condition before its body; its body usually contains an operation that moves the program toward stopping.


A flowchart connects initialization, a loop condition, a helper call, an addition, a counter update, and use of the final total.


Trace the complete program

Example: A club awards two points for an odd-numbered round and four points for an even-numbered round. This complete program totals three rounds.


Java
public class ClubPoints {
    static int pointsForRound(int round) {
        if (round % 2 == 0) {
            return 4;
        } else {
            return 2;
        }
    }

    static int totalPoints(int rounds) {
        int total = 0;
        for (int round = 1; round <= rounds; round++) {
            total = total + pointsForRound(round);
        }
        return total;
    }

    public static void main(String[] args) {
        int result = totalPoints(3);
        System.out.println(result);
    }
}


The remainder operation % identifies even rounds because an even integer leaves remainder zero when divided by two. The helper therefore returns 2, 4, and 2 for rounds 1, 2, and 3. The running totals are 2, 6, and 8 points.


The program begins in main. Its call to totalPoints(3) starts the repeated calculation. Each call to pointsForRound finishes before its returned value is added. A return exits the method currently executing, so returning from the helper resumes the calculation inside totalPoints.


The total is returned after the loop finishes. When round becomes 4, the condition is false, and totalPoints returns 8 to main. The program prints 8 once. Here, static allows these methods to be called directly from the static main method.



What to remember

  • Give each helper one clear contribution to the complete task.
  • Initialize once, update during repetition, and use the completed result afterward.
  • Follow calls into helpers and returned values back to their callers.
  • Check the first iteration, the last iteration, and the condition that stops repetition.

Example: Planning Snack Tokens for Volunteer Shifts

A community event allocates snack tokens for five volunteer shifts. Shifts 1 and 2 receive three tokens each; later shifts receive five tokens each. The program prints the total allocation and a restocking message. An execution trace records the operations and changing values in the order they actually occur.


Java
public class SnackPlan {
    static int tokensForShift(int shift) {
        if (shift <= 2) {
            return 3;
        } else {
            return 5;
        }
    }

    static int totalTokens(int shifts) {
        int total = 0;
        for (int shift = 1; shift <= shifts; shift++) {
            total = total + tokensForShift(shift);
        }
        return total;
    }

    public static void main(String[] args) {
        int total = totalTokens(5);
        System.out.println(total);
        if (total >= 20) {
            System.out.println("Restock");
        } else {
            System.out.println("Enough");
        }
    }
}


Trace the code without changing it. Complete the call to totalTokens before evaluating the restocking decision in main.


a) What is the running total immediately after shift 3 has been processed?

  1. Initialize the running total to zero tokens. For shift 1, the helper's condition is true, so its contribution is ________. For shift 2, the condition is still true, so its contribution is ________.
  2. For shift 3, shift <= 2 is false, so the helper contributes ________. Each returned contribution is added to the existing total.


T1=0+3=3 T2=3+3=6 T3=6+5=11\begin{aligned} T_1 &= 0 + 3 = 3\ T_2 &= 3 + 3 = 6\ T_3 &= 6 + 5 = 11 \end{aligned}


The running total after shift 3 is 11 tokens. This is an intermediate total; the method has not returned yet.


b) What value does totalTokens(5) return?

  1. Continue from the 11 tokens accumulated after shift 3. Shift 4 also takes the helper's else branch, so the running total becomes ________.
  2. Shift 5 contributes ________. Add that contribution to the previous total.


T5=16+5=21 tokensT_5 = 16 + 5 = 21\ \text{tokens}


  1. The loop update changes shift from 5 to 6. The condition shift <= shifts is now 6 <= 5, which is false. Execution continues to the return after the loop.

The method returns 21 tokens. As a check, the first two shifts receive six tokens together, and the remaining three receive fifteen tokens together.


c) What does the complete program print, in order?

  1. The call to totalTokens(5) returns 21, which becomes the value of total in main. The first print statement therefore prints 21.
  2. Evaluate the restocking condition using that completed total. The comparison 21 >= 20 evaluates to ________, so execution enters the first branch.
  3. That branch prints Restock. The else branch is skipped, and no further print statements execute.

The program prints 21 on the first line and Restock on the second line. The helper's return statements supply values to its caller; those statements do not print anything themselves.

An attendance program must inspect six sessions, call pointsForSession(session) once for each session, and print their combined points once. Which arrangement correctly combines initialization, repetition, and output?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A Java program contains the method below, and main later runs the statement int evens = countEvens(9);.


Java
public static int countEvens(int limit) {
    int count = 0;
    for (int i = 1; i <= limit; i++) {
        if (i % 2 == 0) {
            count++;
        }
    }
    return count;
}


The method's return type is , and the name of its only parameter is . In the call countEvens(9), the value 9 supplied by the caller is called an . During that call the loop body runs times, and the call returns .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A school challenge awards points using the Java methods below. Complete the table for challengeTotal(4), entering exact integers. For each stage, record the helper's returned points and the running total immediately after the addition.


Java
static int stagePoints(int stage) {
    if (stage >= 3) {
        return 5;
    } else {
        return 2;
    }
}

static int challengeTotal(int stages) {
    int total = 0;
    for (int stage = 1; stage <= stages; stage++) {
        total = total + stagePoints(stage);
    }
    return total;
}
StageReturned pointsRunning total in points
1
2
3
4

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice