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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: The Complete Cycle of Writing, Testing, and Fixing Java Code →← How Java Reads and Executes Instructions Step by StepNext lesson: The Complete Cycle of Writing, Testing, and Fixing Java Code →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
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
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
How do you avoid off-by-one errors in a for loop?
Why does my while loop run forever in Java?
How many times does the inner body of a nested loop run?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →