Unit 4 - Iteration
Iteration
- Introduction
- While Loops
- For Loops
- Developing Algorithms Using Strings
- Nested Iteration
- Informal Code Analysis
- Hacks
Introduction
Loops are fundamental constructs in programming that allow for the repetition of code. They are essential for performing tasks that require iteration, such as processing elements in arrays or strings, and executing repetitive actions. In this guide, we’ll explore various types of loops—while loops, for loops—and their applications, including how they interact with strings and nested structures. Understanding these concepts is crucial for developing efficient algorithms and solving complex problems in programming.
While Loops
A while loop repeatedly executes a block of code as long as a specified condition remains true. The condition is evaluated before each iteration, and if it is true, the loop’s body runs; if false, the loop terminates. To avoid infinite loops, ensure the condition will eventually become false by modifying it within the loop.
Example:
int i = 0;
while (i < 5) {
System.out.print(i);
i++;
}
Explanation:
- Initialize
i
to 0. - The loop checks if
i
is less than 5. If true, it executes the body. - The body prints
i
and increments it. - After each iteration, the condition is re-evaluated. When
i
reaches 5, the loop stops.
Tracing Table: | i | Output | |-|-| | 0 | 0 | | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 4 |
If the initial condition is false, the loop will not execute. A return
statement inside a while loop will also stop it immediately, regardless of the condition.
Common Uses:
- Identify individual digits of an integer
- Determine a minimum or maximum value
- Compute a sum, average, or mode
For Loops
A for loop provides a concise way to repeat code with initialization, condition-checking, and iteration all in one line. The basic structure in Java is:
for (initialization; condition; iteration) {
// code to be executed
}
- Initialization: Executes once before the loop starts, typically to set up a loop counter.
- Condition: Evaluated before each iteration. If true, the loop body executes; if false, the loop terminates.
- Iteration: Executes after each iteration of the loop body, usually to update the loop counter.
Example:
for (int i = 0; i < 5; i++) {
System.out.print(i);
}
Explanation:
int i = 0;
initializes the loop counteri
.i < 5
is the condition. The loop continues as long asi
is less than 5.i++
incrementsi
after each iteration.
The for loop achieves the same result as a while loop but in fewer lines, making it more compact and often easier to read. All for loops can be converted to while loops and vice versa.
Developing Algorithms Using Strings
Loops can be used to process and analyze strings in various ways. With methods like .length()
and .substring()
, you can perform tasks such as counting characters.
Example: Counting Occurrences of a Character
String str = "computer science";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.substring(i, i+1).equals("e")) {
count++;
}
}
System.out.println(count);
Explanation:
String str = "computer science";
initializes the string.int count = 0;
creates a counter for occurrences of “e”.for (int i = 0; i < str.length(); i++)
iterates over each character in the string.str.substring(i, i+1).equals("e")
checks if the current character is “e”.- If true, increment the count.
Other Uses:
- Reversing a string
- Finding substrings with specific properties
- Checking for specific substrings
Tip: Tracing tables can help keep track of iterations and conditions in loops working with strings.
Nested Iteration
Nested loops involve placing one loop inside another, which is useful for tasks like traversing 2D arrays. The inner loop completes all its iterations before the outer loop moves to the next iteration.
Example:
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
Explanation:
int rows = 5;
sets the number of rows for the pattern.- The outer loop (
for (int i = 1; i <= rows; i++)
) iterates over each row. - The inner loop (
for (int j = 1; j <= i; j++)
) prints asterisks based on the current row number. System.out.println();
moves to the next line after completing the inner loop for each row.
Tip: Use tracing tables to track the iterations of nested loops for complex patterns or calculations.
Informal Code Analysis
Informal code analysis involves examining and understanding code execution without formal tools. This can include manually tracing code execution, predicting output, and identifying logical errors.
Key Techniques:
- Tracing Code: Manually following the flow of execution, step-by-step, to understand how variables change and how loops execute.
- Predicting Output: Anticipating the result of code before running it, based on the logic and structure.
- Identifying Errors: Spotting potential mistakes or inefficiencies by reviewing code logic and flow.
Example of Manual Tracing:
int i = 0;
while (i < 3) {
System.out.print(i);
i++;
}
Tracing Steps:
- Initialize
i
to 0. - Check if
i < 3
(true), print0
, incrementi
to 1. - Repeat:
i < 3
(true), print1
, incrementi
to 2. - Repeat:
i < 3
(true), print2
, incrementi
to 3. - Check
i < 3
(false), exit loop.
Informal analysis helps in understanding code behavior and debugging before deploying formal testing methods.
Additional Resources:
Hacks
Part 1
public class NumberPrinter {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.print(i + " ");
i++;
}
System.out.println();
for (int j = 5; j > 0; j--) {
System.out.print(j + " ");
}
System.out.println();
for (int k = 1; k <= 3; k++) {
for (int l = 1; l <= k; l++) {
System.out.print("*");
}
System.out.println();
}
}
}
Answer the following questions based on the code above:
- a) What will be the output of each loop in the code? Explain how each loop works.
- Answer:
- b) Modify the first while loop so that it prints the numbers in reverse order, from 5 to 1, instead of 1 to 5. Provide the modified code and explain the changes.
- Answer:
Part 2
Situation: You are developing a program to analyze student grades and identify patterns. You need to write methods that use loops to perform these tasks.
(a) Explain how a for loop and a while loop differ in structure and usage. Provide an example of when you might prefer one over the other.
(b) Write a method calculateAverage
that takes an array of integers representing student grades and returns the average grade using a for loop. Next, write a method findHighestGrade
that uses a while loop to find and return the highest grade in the array.
Provide the code for both methods and demonstrate how to call them with an example array of grades.