Lesson 7: Repetitions | Loops - for and foreach
Understanding iterative control structures in Java.
Contents
Laboratory Works
- • Lab 1: FOR loop - Counter Values
- • Lab 2: FOR loop - Compute Factorial
- • Lab 3: NESTED loop - Prime Numbers
Tasks for Independent Work
- • Task 1: Sequence with Step 3
- • Task 2: Symmetrical Sequence
- • Task 3: Count Positives & Negatives
- • Task 4: Sum of Random Numbers
- • Task 5: Sum of Odd Sequence
- • Task 6: Product of Random Numbers
- • Task 7: foreach - Filter Digits
- • Task 8: foreach - Count Vowels (RU)
- • Task 9: Nested Loops - Power Function
- • Task 10: foreach - Append Character
- • Task 11: Nested Loops - Number Pyramid
Introduction to Loops
- • In programming, you often need to use repetition to iterate over items in a collection or to perform the same task multiple times.
- • Java provides several loop structures to implement iteration logic: for loops, while loops, and do-while loops.
Key Concept: Repetition is the third fundamental type of program control structure, following sequence and selection. Repeating steps in programming is called a loop. This section of the course describes three Java loop control statements: while, for, and do-while. The statements to be repeated are called the loop body.
The for Loop
- • The for loop executes a block of code repeatedly until a specified condition evaluates to false.
-
• Syntax:
for ([initializers]; [condition]; [iterator]) { // code to repeat goes here }
- • The [initializers] section initializes the loop counter. The [condition] is checked before each iteration; if true, the loop body executes. The [iterator] section updates the counter after each iteration.
Example:
for (int i = 0; i < 10; i++) { // Code to execute. }
In this example:
i = 0; is the initializer,
i < 10; is the condition, and
i++ is the iterator.
The For-each Loop
- • When iterating over a collection or array, you might not always know its size, especially if it's dynamic. The for-each loop (enhanced for loop) is often a better choice in such cases.
Example 1: Iterating over characters in a String
String str = "loops"; // Process each character in the string: for (char c : str.toCharArray()) { // Code to execute }
Example 2: Iterating over a List of Strings
List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); for (String name : names) { System.out.println(name); }
- • Java stops executing the loop when the end of the collection or array is reached.
Example: Convert a string to uppercase and print each character
String input = "java"; for (char c : input.toCharArray()) { System.out.print(Character.toUpperCase(c) + " "); } // Output: J A V A
When to Use a For-each Loop
| Suitable For | Not Suitable For |
|---|---|
| When you don't need the element index. | When you need access to the element index. |
| When you only need to read or process elements. | When you need to traverse in reverse order. |
| When code readability and simplicity are important. | When you need to modify elements of a primitive array (the loop variable holds a copy). |
| - | When you need complex conditions that depend on the index. |
Nested Loops
One loop can be nested inside another. A nested loop structure consists of one outer loop and one or more inner loops. Each time the outer loop iterates, the inner loops re-enter and run completely.
Example: Multiplication Table using nested for loops
public class MultiplicationTable { public static void main(String[] args) { // Display the table title System.out.println("\t\t\t\tMULTIPLICATION TABLE\n"); // Display column headers for (int j = 1; j <= 9; j++) System.out.print("\t" + j); System.out.println("\n\t_\t_\t_\t_\t_\t_\t_\t_\t_"); // Display row headers and products for (int i = 1; i <= 9; i++) { System.out.print(i + " |"); for (int j = 1; j <= 9; j++) { System.out.printf("\t" + i * j); } System.out.println(); } } }
Program Explanation: The program first displays the table title. The first for loop prints numbers 1 through 9 as column headers, followed by a line of underscores. The second, nested for loop uses variable i for the outer loop (rows) and j for the inner loop (columns). For each value of i, the inner loop displays the product i * j for j = 1, 2, 3, ..., 9.
Laboratory Work
Lab 1: FOR Loop - Displaying Counter Values
Objective: Ask the user to input a number (N). Create a simple for loop with N repetitions that displays the values of the loop counter.
Expected Output:
Please enter a number and press Enter 3 The result: Counter is at: 1 Counter is at: 2 Counter is at: 3 Please enter a number and press Enter 1 The result: Counter is at: 1
File Name: L7Lab1.java
Class Name: L7Lab1
Algorithm:
- Create a new Java file named L7Lab1.java.
- Import the Scanner class: import java.util.Scanner;
- Define the class L7Lab1 with a main method.
- Inside the main method, create a Scanner object for input.
- Prompt the user with System.out.println("Please enter a number and press Enter");
- Read the integer input and store it in a variable N.
- Print "The result:".
- Create a for loop: for(int counter = 1; counter <= N; counter++)
- Inside the loop, print the counter value: System.out.println("Counter is at: " + counter);
- Run the program (e.g., press F5 in your IDE).
- Test with different input values.
- Place the task description as a comment at the top of the file.
- Upload the file to the learning management system.
Lab 2: FOR Loop - Compute Factorial
Objective: Write a program that calculates and displays the factorial of an entered integer.
Expected Output (Example):
Enter an integer: 5 5! is 120
File Name: L7Lab2.java
Class Name: L7Lab2
Algorithm:
- Create a new Java file named L7Lab2.java.
- Import the Scanner class: import java.util.Scanner;
- Define the class L7Lab2 with a main method.
- Inside main, create a Scanner object.
- Prompt the user: System.out.print("Enter an integer: ");
- Read the integer input into a variable n.
- Initialize a variable product = 1 to accumulate the factorial.
- Create a for loop: for (int i = n; i > 1; --i)
- Inside the loop, multiply product by i: product *= i;
- After the loop, print the result: System.out.println(n + "! is " + product);
- Run and test the program.
- Add the task description as a comment at the file's beginning.
- Upload the file.
Lab 3: NESTED Loop - Prime Numbers
Objective: Create a nested for loop to find and display all prime numbers less than 100 (starting from 2).
Expected Output (Excerpt):
Prime numbers: 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime ... 97 is prime
File Name: L7Lab3.java
Class Name: L7Lab3
Algorithm:
- Create a new Java file named L7Lab3.java.
- Define the class L7Lab3 with a main method.
- Print the header: System.out.println("Prime numbers:");
- Declare two integer variables, e.g., outer and inner.
- Create an outer for loop: for (outer = 2; outer < 100; outer++)
- Inside it, create an inner for loop: for (inner = 2; inner <= (outer / 2); inner++)
- Inside the inner loop, check divisibility: if ((outer % inner) == 0) break;
- After the inner loop, check if inner > (outer / inner). If true, outer is prime. Print it.
- Run the program to see all primes under 100.
- Add a comment with the task description.
- Upload the file.
Prime Number Theory: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not prime is called a composite number. Primes are fundamental in number theory due to the Fundamental Theorem of Arithmetic: every integer greater than 1 is either prime itself or can be uniquely factorized as a product of primes.
Tasks for Independent Work
Task 1: Sequence with Step 3
To do: Output the sequence: -3 0 3 6 9 12 15 18 21 24. Use a for loop with an iterator step of 3.
Note: Use counter += 3 as the iterator.
Expected Output:
File Name: L7Task1.java
Task 2: Symmetrical Sequence
To do: Output the sequence: 1 2 3 4 ... 99 100 99 ... 3 2 1.
Note 1: Create two for loops: the first for 1 2 ... 100, the second for 99 ... 2 1 (using i--).
Expected Output (Excerpt):
1 2 3 4 5 ... 99 100 99 ... 4 3 2 1
File Name: L7Task2.java
Task 3: Count Positive and Negative Numbers
To do: 10 integers are entered. Output the count of positive and negative numbers among them.
Note: Use a for loop for input. Check each number inside the loop. Use two counters.
Expected Output (Example with random numbers):
counter_positive = 6,
counter_negative = 4
File Name: L7Task3.java
Task 4: Sum of Random Numbers
To do: 10 integers are randomly generated. Output these numbers and their sum.
Note 1: Use a for loop and a variable sum.
Note 2: Use (int)(Math.random() * 10) to generate integers 0-9. Adapt for a range that includes negatives if required.
Expected Output (Example):
File Name: L7Task4.java
Task 5: Sum of Odd Sequence
To do: Calculate the sum of the sequence: 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19. Generate the numbers using a loop; do not enter them.
Note: Use a variable named sum.
Expected Output:
File Name: L7Task5.java
Task 6: Product of Random Real Numbers
To do: 10 real numbers are entered or randomly generated. Output the numbers and their product.
Note 1: Use a for loop and a variable product.
Note 2: Initialize product as a double (e.g., 1.0).
Note 3: For random generation, you can use Math.random() * 20 for a range like 0.0 to 20.0.
Expected Output (Example):
product = 598166786228,4310
File Name: L7Task6.java
Task 7: For-each - Filter Digits from String
To do: Extract and output only the digits from a given string. Use a for-each loop.
Note: Use the Character.isDigit() method.
Expected Output:
>> abc123def456
123456
File Name: L7Task7.java
Task 8: For-each - Count Vowels in a String (Russian)
To do: Count the number of vowel letters (а, е, и, о, у, ы, э, ю, я) in a given string (consider lowercase only).
Note: Use indexOf() to check if a character is in the vowel string.
Expected Output:
>> programm
vowels: 2
File Name: L7Task8.java
Task 9: Nested Loops - Power Function
To do: For every x in the range [2;8], find the value of z(x,y) = xy. The variable y ranges from 2 to 5.
Note: Use nested for loops: outer for x, inner for y. Use Math.pow(x, y) or a manual calculation loop.
Expected Output (Excerpt):
z(x,y) = 2^2 = 4 z(x,y) = 2^3 = 8 z(x,y) = 2^4 = 16 z(x,y) = 2^5 = 32 z(x,y) = 3^2 = 9 z(x,y) = 3^3 = 27 z(x,y) = 3^4 = 81 z(x,y) = 3^5 = 243 ...
File Name: L7Task9.java
Task 10: For-each - Append Character
To do: Ask the user to enter a text and then a character. Output each character of the text with the entered character appended to it. Use a for-each loop.
Expected Output:
Enter the text, please: >> Hello world! Enter a character to add, please: >> & H& e& l& l& o& & w& o& r& l& d& !&
File Name: L7Task10.java
Task 11: Nested Loops - Number Pyramid
To do: Write nested loops that display the following output pattern.
Note: Display the upper and lower parts using separate nested loops.
Expected Output:
0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
File Name: L7Task11.java