Nested Loops and Mathematical Programming in Java

Course Information and Lesson Overview

  • Institution: Sulaimani Polytechnic University (SPU) / زانكوى بولى ءة كنى كى سلى مانى

  • College: Technical College of Informatics

  • Department: Database Technology Department

  • Lesson: Lesson 4: Nested Loops in Programming

  • Instructor: Askandar H. Amin

  • Date: April, 2026

Content Areas

  • Creating games using logic

  • Performing mathematics using loops

  • Distinction between Print and Print-line (println)

  • Utilization of the Math Function library

  • Structural implementation of Nested Loops

  • Integrating conditions inside loops

  • Matrix conceptualization and representation

  • Useful practical exercises

Interactive Logic: Guessing Game Loop

This section challenges the student to identify loop types and modify behavior:

  • What is the type of loop?: The provided code uses a for(; ; ) structure, which is an infinite loop unless terminated by a break statement.

  • Variable Inclusion: A challenge is posed to add a variable specifically to count the number of trials the user takes to guess the number.

Guessing Game Code Example
import java.util.Scanner;

public class nestedLoop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Try guessing the number: ");
        int input;
        for (; ; ) {
            input = sc.nextInt();
            if (input == 27) {
                System.out.println("Correct!");
                break;
            }
            System.out.print("Try again: ");
        }
    }
}

Mathematical Operations Using Loops

Loops are highly effective for calculating sums. Using the example where n=5n=5, the total sum from 1 to 5 is calculated as 1+2+3+4+5=151+2+3+4+5=15.

Mathematical Formulas
  • The general equation for the sum of the first nn integers is: n(n+1)2\frac{n(n+1)}{2}

  • Example 1 (n=5n=5): 5(6)2=15\frac{5(6)}{2} = 15

  • Example 2 (n=100n=100): While calculating 1+2+3++1001+2+3+\dots+100 manually is difficult, the formula provides the answer immediately: 100(101)2=5050\frac{100(101)}{2} = 5050

  • Exercise for n=1000n=1000: Construct a loop to calculate the sum when n=1000n=1000:

for (int i = 1; i < 1000; i++) {
    // Implementation of sum logic goes here
}

Loop Control and Variable Tracking

Understanding the output of different loop configurations is vital for mastering flow control.

  • Standard Increment Loop:

for (int i = 0; i <= 10; i++) {
    System.out.println(i);
}
  • Standard Decrement Loop:

for (int i = 10; i >= 0; i--) {
    System.out.println(i);
}
  • Multi-Variable Loop:

for (int i = 0, j = 10; i <= 10; i++, j--) {
    System.out.println("i=" + i + "  j=" + j);
}
  • Logic Challenge: Determine the output if the loop condition is changed from i10i \leq 10 to i==ji == j.

Print and PrintLine Management

Proper use of System.out.print() versus System.out.println() is necessary for formatting.

User Input within Loops

Example code for entering names:

Scanner sc = new Scanner(System.in);
System.out.println("Enter five names:");
for (int i = 1; i <= 5; i++) {
    System.out.print("name " + i + " is: ");
    sc.next();
}

Execution Results:

  • Enter five names:

  • name 11 is: Ali

  • name 22 is: Basan

  • name 33 is: Kurdonia

  • name 44 is: Sazy

  • name 55 is: Sarbast

Critical Warning: Using a Scanner inside a loop can be effective but requires care. Specifically, note that if the scanned value is not assigned to a variable (or if the variable is overwritten in every iteration), the data is not stored and will be lost.

Java Math Library Functions

The Math class provides several built-in methods for complex operations:

  • Minimum and Maximum:

    • Math.max(5, 10) returns 1010

    • Math.min(5, 10) returns 55

  • Roots and Exponents:

    • Math.sqrt(64) returns 8.08.0

    • Math.pow(2, 8) returns 256.0256.0

  • Absolute Values:

    • Math.abs(-4.7) returns 4.74.7

    • Math.abs(4.7) returns 4.74.7

  • Rounding and Approximations:

    • Math.round(4.4) returns 44

    • Math.round(4.5) returns 55

    • Math.round(4.6) returns 55

    • Math.ceil(4.1) returns 5.05.0

    • Math.ceil(4.7) returns 5.05.0

    • Math.floor(4.1) returns 4.04.0

    • Math.floor(4.9) returns 4.04.0

  • Random Number Generation:

    • Math.random() returns a double between 0.00.0 and 1.01.0 (e.g., 0.55479757759213090.5547975775921309).

    • To get a range from 00 to 1010, use: (int)(Math.random() * 11).

Educational Note: It is considered good practice to attempt writing the logic for these functions (especially max, min, sqrt, pow, round, and random) yourself to understand the underlying algorithms.

Nested Loop Structure and Syntax

A nested loop is a loop inside another loop.

Syntax
for (initialization; condition; update) {
    for (initialization; condition; update) {
        // loop's body
    }
}
Iteration Calculation
  • Example:

for (int i = 0; i <= 5; i++) {
    for (int j = 0; j <= 5; j++) {
        System.out.println(i + " " + j);
    }
}
  • Analysis: Consider how many total iterations occur (outer iterations ×\times inner iterations) and how the placement of code inside or outside the inner loop affects the output.

Variations in Other Loop Types
  • While-While:

while (condition) {
    while (condition) {
        // your code
    }
}
  • Do-While-Do-While:

do {
    do {
        // your code
    } while (condition);
} while (condition);

Nested Loop Output Formats

Different println placements result in different visual structures.

Row-Based Printing Example
for (int i = 0; i < 5; i++) {
    System.out.println("row: " + i);
    for (int j = 0; j < 5; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}

Output:

  • row: 0

  • 0 1 2 3 4

  • row: 1

  • 0 1 2 3 4

  • … (repeated for rows 2, 3, and 4)

Column-Labeled Printing Example
for (int i = 0; i <= 5; i++) {
    System.out.print("row " + i + ":");
    for (int j = 0; j <= 5; j++) {
        System.out.print("Column:" + j + " ");
    }
    System.out.println();
}

Matrix Conceptualization

Matrices are vital for understanding coordinates in programming.

Coordinate Matrix Code
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        System.out.print("(" + i + ", " + j + ") ");
    }
    System.out.println();
}

Visual Matrix Layout (5x5):

  • (0,0) (0,1) (0,2) (0,3) (0,4)

  • (1,0) (1,1) (1,2) (1,3) (1,4)

  • (2,0) (2,1) (2,2) (2,3) (2,4)

  • (3,0) (3,1) (3,2) (3,3) (3,4)

  • (4,0) (4,1) (4,2) (4,3) (4,4)

Key Matrix Insights:

  • Understand the role of brackets (or lack thereof) in loop bodies.

  • A matrix allows you to select specific angles (diagonals) and data points.

  • You can create different matrices by initializing ii and jj with different starting values.

Conditional Logic Within Loops

By inserting conditions like if(i == j), you can isolate specific patterns within a matrix.

Pattern Matching Example
for (int i = 0; i <= 5; i++) {
    for (int j = 0; j <= 5; j++) {
        if (i == j) {
            System.out.print(i);
        } else {
            System.out.print(" ");
        }
    }
    System.out.println("");
}

Comparison of Loops and Conditions:

  • Both execute exactly one statement immediately following them (unless a block {} is used).

  • This specific code prints the value of ii only along the diagonal from top-left to bottom-right.

Matrix Pattern Challenges

Students are encouraged to find patterns in coordinate grids.

Example Matrix Grid:

  • row 0: [0,0 0,1 0,2 0,3 0,4 0,5]

  • row 1: [1,0 1,1 1,2 1,3 1,4 1,5]

  • row 2: [2,0 2,1 2,2 2,3 2,4 2,5]

  • row 3: [3,0 3,1 3,2 3,3 3,4 3,5]

  • row 4: [4,0 4,1 4,2 4,3 4,4 4,5]

  • row 5: [5,0 5,1 5,2 5,3 5,4 5,5]

Exercises for Nested Loops

Tasks to practice loop logic by printing star patterns:

  1. Inverse Triangle (Right-aligned): ****** ***** **** *** ** * &nbsp;&nbsp;&nbsp;&nbsp;

  2. Incrementing Stars per Row:     * ** *** **** ***** ******

  3. Spaced Single Stars:     * * * * * * (Horizontal or vertical distribution logic)

  4. Standard Right-Angled Triangle: * ** *** **** ***** ****** &nbsp;&nbsp;&nbsp;&nbsp;

  5. Descending Blocks:     ***** **** *** ** *

  6. Diagonal/Spaced Alignment:     * * * * * *