Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Basic Programming Language Constructs
  6. Lesson # 7: For and Foreach

Lesson # 7: For and Foreach

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:

  1. Create a new Java file named L7Lab1.java.
  2. Import the Scanner class: import java.util.Scanner;
  3. Define the class L7Lab1 with a main method.
  4. Inside the main method, create a Scanner object for input.
  5. Prompt the user with System.out.println("Please enter a number and press Enter");
  6. Read the integer input and store it in a variable N.
  7. Print "The result:".
  8. Create a for loop: for(int counter = 1; counter <= N; counter++)
  9. Inside the loop, print the counter value: System.out.println("Counter is at: " + counter);
  10. Run the program (e.g., press F5 in your IDE).
  11. Test with different input values.
  12. Place the task description as a comment at the top of the file.
  13. 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:

  1. Create a new Java file named L7Lab2.java.
  2. Import the Scanner class: import java.util.Scanner;
  3. Define the class L7Lab2 with a main method.
  4. Inside main, create a Scanner object.
  5. Prompt the user: System.out.print("Enter an integer: ");
  6. Read the integer input into a variable n.
  7. Initialize a variable product = 1 to accumulate the factorial.
  8. Create a for loop: for (int i = n; i > 1; --i)
  9. Inside the loop, multiply product by i: product *= i;
  10. After the loop, print the result: System.out.println(n + "! is " + product);
  11. Run and test the program.
  12. Add the task description as a comment at the file's beginning.
  13. 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:

  1. Create a new Java file named L7Lab3.java.
  2. Define the class L7Lab3 with a main method.
  3. Print the header: System.out.println("Prime numbers:");
  4. Declare two integer variables, e.g., outer and inner.
  5. Create an outer for loop: for (outer = 2; outer < 100; outer++)
  6. Inside it, create an inner for loop: for (inner = 2; inner <= (outer / 2); inner++)
  7. Inside the inner loop, check divisibility: if ((outer % inner) == 0) break;
  8. After the inner loop, check if inner > (outer / inner). If true, outer is prime. Print it.
  9. Run the program to see all primes under 100.
  10. Add a comment with the task description.
  11. 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:

The sequence : -3 0 3 6 9 12 15 18 21 24

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):

The sequence :
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):

1 -5 -12 2 3 9 -1 9 5 -8
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):

1 -5 -12 2 3 9 -1 9 5 -8 => sum = 3

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:

1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 => sum = 100

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):

14,8000 17,1000 19,7000 14,2000 13,5000 16,8000 11,0000 17,2000 17,9000 11,0000
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:

Enter a string
>> 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:

Enter a string:
>> 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

© Educational Platform for Students. Lesson 7: Loops - for and foreach.

◄ Lesson #6: Characters and Strings in Java
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • МО_4курс

        • KP

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

            • AssignmentLesson 1. Programming on Java in Microsoft Visual ...

            • AssignmentLesson 2. Data Types and Type Casting. Boolean type

            • AssignmentLesson 3. Java Conditional statement IF

            • AssignmentLesson 4: Ternary Operator and Switch Statement

            • AssignmentLesson #5: Mathematical Functions in Java

            • AssignmentLesson #6: Characters and Strings in Java

            • AssignmentLesson # 7: For and Foreach

          • Methods (functions)

          • Arrays

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • МО (ПО)

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика