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 abreakstatement.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 , the total sum from 1 to 5 is calculated as .
Mathematical Formulas
The general equation for the sum of the first integers is:
Example 1 ():
Example 2 (): While calculating manually is difficult, the formula provides the answer immediately:
Exercise for : Construct a loop to calculate the sum when :
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 to .
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 is: Ali
name is: Basan
name is: Kurdonia
name is: Sazy
name 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)returnsMath.min(5, 10)returns
Roots and Exponents:
Math.sqrt(64)returnsMath.pow(2, 8)returns
Absolute Values:
Math.abs(-4.7)returnsMath.abs(4.7)returns
Rounding and Approximations:
Math.round(4.4)returnsMath.round(4.5)returnsMath.round(4.6)returnsMath.ceil(4.1)returnsMath.ceil(4.7)returnsMath.floor(4.1)returnsMath.floor(4.9)returns
Random Number Generation:
Math.random()returns adoublebetween and (e.g., ).To get a range from to , 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 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 and 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 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:
Inverse Triangle (Right-aligned):
****** ***** **** *** ** * Incrementing Stars per Row:
* ** *** **** ***** ******Spaced Single Stars:
* * * * * *(Horizontal or vertical distribution logic)Standard Right-Angled Triangle:
* ** *** **** ***** ****** Descending Blocks:
***** **** *** ** *Diagonal/Spaced Alignment:
* * * * * *