Automating Repetitive Tasks Using Conditional Looping Mechanisms

UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 1.3 Free with a free account

Automating Repetitive Tasks Using Conditional Looping Mechanisms

Data Structures and Algorithms · Chapter 1: Getting Started with JavaSection 1.3 · lesson 3 of 8712 min · free with a free account

← How Java Reads and Executes Instructions Step by StepNext lesson: The Complete Cycle of Writing, Testing, and Fixing Java Code →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

In this lesson

Write while, do-while and for loops that stop when they should.

  • Identify the initialization, condition, body and update of any loop
  • Compare while, do-while and for loops and choose the clearest form
  • Diagnose off-by-one errors and infinite loops, including skipped updates and decimal drift
  • Apply accumulator, counter and search patterns, including nested loops and labeled break

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,888 words). Read along, or search it.

Opening Question

Printing a Pass Number Many Times

A program must print a pass number five times. Five separate print lines would do. But what if it's five hundred, or a number the user types? Copying lines stops being a plan. What you want to say is the idea: start at one, and keep printing while the number is five or less, adding one each time. That sentence is a loop. Run it: pass one to pass five. Change the five to five hundred, and nothing else changes.

Loop Anatomy

Four Parts of Every Loop

Every loop, whatever its form, has the same four parts. The initialization gives it a starting state, before the first pass. The condition is tested to decide whether another pass happens. The body is the work repeated each pass. And the update changes something, so the condition can eventually become false. Here's the rule that prevents most loop bugs. A loop ends only when the body changes what the condition is looking at. If you can't point to that line, the loop isn't finished.

Worked Example

Tracing a While Loop Sum

The while loop is the plainest form. Java tests the condition. If it's true, the body runs once, and Java goes back to test again. If it's false, the loop is skipped. This one adds up one to five. Sum collects the total, and i walks through the numbers. Trace it, a pass at a time. Pass one: i is one, so sum becomes one, and i becomes two. Pass two: sum becomes three, and i, three. Three more passes bring sum to six, then ten, then fifteen, and i to six. Now the test finds six isn't five or less. The loop ends, and the program prints sum equals fifteen.

Loop Conditions

Counters, Sentinels and Program State

Not every loop counts. The condition can watch a counter reaching a limit, like printing one to five. Watch for a limit one too high, or too low. It can watch for a sentinel: a special input that means stop, like minus one. Watch for adding the sentinel to the total. Or it can watch any program state, like halving a value until it drops below one. Watch for a state that never moves toward the stop.

Technique

Sentinel Loops and the Priming Read

A sentinel loop needs a small trick. The first value is read before the loop starts, so the condition has something to test. That's a priming read. Then the next value is read at the very end of the body, so the sentinel is tested before it's ever added. Feed it four, nine, two, then minus one: total fifteen. The minus one stopped the loop, and was never added. And because a while loop tests first, it can run zero times. Type minus one straight away, and the total is zero. That's not a bug. It's exactly right.

Do-While Loop

Body First, Test After

The do-while loop flips the order. The body runs once, and only then is the condition tested. So it always makes at least one pass. That's exactly what checking input needs: the program must ask once, before it can judge the answer. Type fifteen, then zero, then seven. Fifteen and zero are out of range, so it asks again. Seven is accepted. N is declared before the loop, because a variable declared inside the braces isn't visible to the condition after them.

Common Mistake

The Do-While Closing Semicolon

One more detail. The do-while's closing line ends with a semicolon, which is easy to forget, because no other loop needs one there. Leave it out, and the compiler stops: semicolon expected. So the two loops differ only in where the test sits. While tests first, and can run zero times. Do-while tests after, and always runs once.

For Loop

Three Parts in One Header

The for loop packs three of the parts into one header: initialization, condition, and update. A reader sees how it starts, stops, and moves, all in one line. The order matters. Initialize once. Then test, run the body, update. Test, body, update, until the test is false. Here, three passes, a countdown from three to liftoff, and a counter that moves in steps of two. Run it. Each header says, at a glance, exactly what the loop will do.

Variable Scope

Header Counters Vanish After the Loop

A counter declared in the header exists only inside the loop. Use it after the closing brace, and the compiler can't find it. If you need the final value afterwards, declare the variable before the loop, and leave that part of the header empty. Now it prints the last value, three.

Common Mistake

Off-by-One Errors in Loop Bounds

The most common loop mistake is the off-by-one error: one pass too many, or one too few, because the start or the comparison is slightly off. Starting at zero with less than five gives five passes. Change it to less than or equal, and you get six. Starting at one with less than or equal to five gives five again. With a step of one, the passes are last minus first, plus one. So to repeat n times, start at zero and use less than n, or start at one and use less than or equal. Mixing them is where the extra pass comes from.

Quick Check

Counting Passes From Five to Twelve

Quick check, with a new header. A counter starts at five, and runs while it's less than or equal to twelve, one step at a time. How many passes does the loop make? Pause, and predict. It makes eight passes. The last value is twelve and the first is five. Twelve minus five, plus one. Seven forgets the plus one, and twelve counts from one instead of from five. The habit worth building: check the first pass and the last pass by hand.

Loop Control

Leaving Early With Break and Continue

Sometimes the header isn't the only reason to stop, or to skip ahead. Break leaves the loop immediately. Continue abandons this pass, and jumps to the next one. Here, break ends a search the moment it succeeds: the first multiple of seven above fifty is fifty-six. No more numbers are checked. And continue skips the multiples of three, and carries on with the rest: one, two, four, five, and so on.

Common Mistake

Continue Skipping a While Update

Continue has a danger. In a for loop, it jumps to the update in the header, so the counter still moves. In a while loop, the update lives in the body. Here, n starts at zero, which is even. Continue jumps back to the test, skipping n plus plus. So n stays zero forever. Run it, and nothing happens. The program doesn't crash: it just never ends. In a terminal, Control C stops it. In an IDE, use the red stop button. The repair: move the update above the continue. Now every pass moves n, and the odd numbers print.

Diagnosis

Common Causes of Infinite Loops

An infinite loop is one whose condition never becomes false. Nearly every one comes from a handful of causes. A missing update. An update moving the wrong way, like adding when the limit is below. And a stray semicolon after the header, which makes the body empty. The skipped update you just saw. And the one that surprises almost everyone: an exact test on a decimal counter.

Common Mistake

Decimal Counters That Never Match

Point one can't be stored exactly in binary, so adding it again and again drifts. This loop waits for x to equal one exactly. It has a guard, so it stops after twelve passes. Run it: after ten additions, x is point nine nine nine, and so on. It walks right past one, without ever equaling it. Count with an int, or test with less than, instead of not equal.

Deliberate Pattern

While True With a Break

Not every endless loop is a mistake. While true is deliberate. It relies on a break inside the body to leave. That's a fair choice when the stopping test is awkward to write as one condition. This one doubles n until it passes a hundred: one twenty-eight. And while you debug a loop, add a temporary pass counter. Stopping after a few hundred passes keeps a mistake from freezing your machine.

Nested Loops

Rows and Columns of Products

A loop's body can hold another loop. The inner loop runs completely, from its first pass to its last, every time the outer loop makes one pass. Here, the outer loop picks the row, and the inner loop walks across five columns. Percent four d right-aligns each product in four characters. Four rows of five: the inner body runs four times five, twenty times.

Worked Example

Triangle Patterns and Labeled Break

The inner limit doesn't have to stay fixed. Here it depends on the outer counter, so row one prints one star, row two prints two, and so on. That makes a triangle. The inner body runs one, plus two, plus three, plus four: ten times. And a plain break leaves only the loop it sits in. To leave both at once, label the outer loop, and name that label in the break. Here, it stops at the first product of four: row two, column two.

Loop Patterns

Accumulators and Counters

Most loops do one of three jobs: gather a value, count something, or look for something. An accumulator starts where it can't disturb the first update. Zero for a sum, since adding zero changes nothing. Sum of one to a hundred: five thousand fifty. One for a product, since multiplying by one changes nothing. Six factorial is seven twenty. And a counter is an accumulator that adds one, but only when an item matches. Up to a hundred, there are fourteen multiples of seven.

Search Pattern

Deciding After the Loop Ends

A search must decide after the loop, not inside it. Report not found inside the body, and it prints for every candidate that fails. So this search records what it finds. Divisor starts at minus one, meaning nothing found yet. The first match is saved, and break stops the loop. One check afterwards reports the outcome. For ninety-one, the smallest divisor is seven. Change the target to ninety-seven, and nothing is found: it's prime.

Quick Check

Inner Loop That Starts at R

Quick check, with a new nested loop. The outer counter r runs from one to three. The inner counter starts at r, and runs up to four. How many times does the inner body run? Pause, and predict. The inner body runs nine times. When r is one, c runs from one to four: four passes. When r is two, three passes. When r is three, two. Four, plus three, plus two. Twelve treats the inner loop as fixed, three times four. Six adds one, two and three, as if the inner limit grew with r.

Decision Guide

Choosing For, While or Do-While

Any of the three loops can imitate the others, so the choice is about readability. Two questions settle most cases. Do you know how many passes you need before the loop starts? Then use for: a table of one to twelve, or exactly twenty repeats. If not, must the body run once before any check? Then do-while: keep asking for a password until it's right. Otherwise, while: read numbers until the user types zero, or halve a value until it's below one. And to try up to three times, stopping early on success, use for, with break.

Key Takeaways

Loop Parts, Forms and Patterns

To sum up. Every loop has an initialization, a condition, a body, and an update that moves it toward stopping. While tests first, and can run zero times. Do-while runs once before testing. For puts the count in one header. Check the first pass and the last pass, to catch off-by-one errors. And most loops accumulate, count, or search. A search decides after the loop ends.

Think About It

Password Attempts With a Lockout

Something to think about. A program must keep asking for a password until it's right, but lock the account after five wrong tries. Which loop form would you choose, and what goes in its condition?

About Data Structures and Algorithms at UPI Study

Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms

Why take it here

Why students take Data Structures and Algorithms with UPI Study

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Automating Repetitive Tasks Using Conditional Looping Mechanisms

What is the difference between a while loop and a do-while loop in Java?
A while loop tests its condition before each pass, so it can run zero times, while a do-while loop runs its body once and only then tests. That makes do-while a good fit for checking input, where the program must ask before it can judge the answer. Unlike other loops, a do-while ends with a semicolon after its condition, as in while (n < 1 || n > 10);
How do you avoid off-by-one errors in a for loop?
Check the first pass and the last pass by hand. With a step of one, the number of passes is last minus first, plus one, so a counter from 5 to 12 inclusive makes 8 passes. To repeat n times, start at 0 and test i < n, or start at 1 and test i <= n. Mixing the two styles, such as starting at 0 with i <= n, adds one extra pass.
Why does my while loop run forever in Java?
A loop runs forever when its condition never becomes false. Common causes are a missing update, an update moving the wrong way, a stray semicolon after the header that leaves the body empty, a continue that jumps past the update in a while loop, and an exact test such as x != 1.0 on a counter that keeps adding 0.1. In a terminal, Control C stops the stuck program.
How many times does the inner body of a nested loop run?
The inner loop runs completely every time the outer loop makes one pass, so with fixed limits you multiply: 4 rows of 5 columns run the inner body 20 times. When the inner limit depends on the outer counter, add the passes instead. For r from 1 to 3 with an inner counter c running from r up to 4, the inner body runs 4 + 3 + 2, or 9 times.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Data Structures and Algorithms.

87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Data Structures and Algorithms
3 credits · NCCRS
Enroll →