Java Programming
Lecture 06: Control Flow - Loop Statements
Course: 4343203 - Java Programming
GTU Semester 4 | Unit 1
Learning Objectives:
- Master for, while, and do-while loop structures
- Understand loop initialization, condition, and increment
- Learn nested loops and pattern programming
- Apply loop control statements (break, continue)
- Solve iterative programming problems
Understanding Loop Statements
Loop Statements allow repeated execution of a block of code as long as a specified condition remains true.
Types of Loops:
- for loop - Known number of iterations
- while loop - Entry-controlled loop
- do-while loop - Exit-controlled loop
- enhanced for loop - For arrays/collections
Key Components:
- Initialization: Starting point
- Condition: Loop continuation test
- Update: Loop variable modification
- Body: Statements to execute
for Loop
Syntax & Structure:
for (initialization; condition; update) {
// loop body
}
// Components breakdown:
// 1. initialization - executed once
// 2. condition - checked before each iteration
// 3. update - executed after each iterationBasic Examples:
// Print numbers 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
// Count down from 10 to 1
for (int i = 10; i >= 1; i--) {
System.out.println("Countdown: " + i);
}
// Even numbers from 2 to 20
for (int i = 2; i <= 20; i += 2) {
System.out.println("Even: " + i);
}for Loop Execution Flow:
Practical Applications:
// Sum of first n natural numbers
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum: " + sum); // 55
// Factorial calculation
int number = 5;
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println(number + "! = " + factorial); // 120while Loop
Syntax & Characteristics:
while (condition) {
// loop body
// update statement (if needed)
}
// Entry-controlled loop:
// - Condition checked before execution
// - May not execute at all if condition is false
// - Used when number of iterations is unknownBasic Examples:
// Print numbers 1 to 5
int i = 1;
while (i <= 5) {
System.out.println(i);
i++; // Don't forget to update!
}
// Input validation loop
Scanner scanner = new Scanner(System.in);
int number;
while (true) {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
if (number > 0) {
break; // Exit loop when valid input
}
System.out.println("Please enter a positive number!");
}Real-world Applications:
// Password verification system
String correctPassword = "secret123";
String userInput = "";
Scanner scanner = new Scanner(System.in);
int attempts = 0;
int maxAttempts = 3;
while (!userInput.equals(correctPassword) && attempts < maxAttempts) {
System.out.print("Enter password: ");
userInput = scanner.nextLine();
attempts++;
if (!userInput.equals(correctPassword)) {
int remaining = maxAttempts - attempts;
if (remaining > 0) {
System.out.println("Incorrect! " + remaining + " attempts left.");
}
}
}
if (userInput.equals(correctPassword)) {
System.out.println("Access granted!");
} else {
System.out.println("Access denied! Too many failed attempts.");
}Important: Always ensure the loop condition will eventually become false to avoid infinite loops!
do-while Loop
Syntax & Key Features:
do {
// loop body
// update statement (if needed)
} while (condition);
// Exit-controlled loop:
// - Body executed at least once
// - Condition checked after execution
// - Notice the semicolon after while!Basic Examples:
// Menu system - executes at least once
int choice;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("\n=== MENU ===");
System.out.println("1. Option A");
System.out.println("2. Option B");
System.out.println("3. Exit");
System.out.print("Enter choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1: System.out.println("You chose A"); break;
case 2: System.out.println("You chose B"); break;
case 3: System.out.println("Goodbye!"); break;
default: System.out.println("Invalid choice!");
}
} while (choice != 3);Practical Applications:
// Number guessing game
Random random = new Random();
int secretNumber = random.nextInt(100) + 1; // 1-100
int guess;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Guess the number between 1-100!");
do {
System.out.print("Enter your guess: ");
guess = scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("Too low! Try higher.");
} else if (guess > secretNumber) {
System.out.println("Too high! Try lower.");
} else {
System.out.println("Congratulations! You got it!");
System.out.println("It took you " + attempts + " attempts.");
}
} while (guess != secretNumber);
// Dice rolling until double 6
Random dice = new Random();
int dice1, dice2;
int rolls = 0;
do {
dice1 = dice.nextInt(6) + 1;
dice2 = dice.nextInt(6) + 1;
rolls++;
System.out.println("Roll " + rolls + ": " + dice1 + ", " + dice2);
} while (dice1 != 6 || dice2 != 6);
System.out.println("Double 6! It took " + rolls + " rolls.");Enhanced for Loop (for-each)
Syntax for Arrays:
// Traditional for loop
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Enhanced for loop (for-each)
for (int num : numbers) {
System.out.println(num);
}Array Processing Examples:
// Sum of array elements
int[] marks = {85, 90, 78, 92, 88};
int total = 0;
for (int mark : marks) {
total += mark;
}
double average = total / (double) marks.length;
System.out.println("Average: " + average);
// Find maximum in array
int[] values = {15, 23, 8, 45, 12, 67, 34};
int max = values[0];
for (int value : values) {
if (value > max) {
max = value;
}
}
System.out.println("Maximum: " + max);String Array Processing:
// Process array of strings
String[] subjects = {"Math", "Physics", "Chemistry", "Biology"};
System.out.println("Subjects offered:");
for (String subject : subjects) {
System.out.println("- " + subject);
}
// Count specific elements
String[] colors = {"red", "blue", "green", "red", "yellow", "red"};
int redCount = 0;
for (String color : colors) {
if (color.equals("red")) {
redCount++;
}
}
System.out.println("Red appears " + redCount + " times");2D Array Processing:
// Process 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Matrix elements:");
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}Advantages of Enhanced for Loop:
- Cleaner, more readable code
- No array bounds checking needed
- Cannot accidentally modify loop variable
- Works with collections too
Nested Loops
Basic Nested Loop Structure:
// Outer loop controls rows
for (int i = 1; i <= 3; i++) {
System.out.println("Outer loop: " + i);
// Inner loop controls columns
for (int j = 1; j <= 4; j++) {
System.out.println(" Inner loop: " + j);
}
}Multiplication Table:
// Generate multiplication tables 1-5
for (int table = 1; table <= 5; table++) {
System.out.println("\nTable of " + table + ":");
for (int i = 1; i <= 10; i++) {
int result = table * i;
System.out.println(table + " x " + i + " = " + result);
}
}2D Array Operations:
// Initialize and display 2D array
int rows = 3, cols = 4;
int[][] matrix = new int[rows][cols];
// Fill matrix with values
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = (i + 1) * (j + 1);
}
}
// Display matrix
System.out.println("Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}Finding Patterns:
// Find all prime number pairs (twin primes)
for (int i = 2; i <= 100; i++) {
if (isPrime(i) && isPrime(i + 2)) {
System.out.println("Twin primes: " + i + ", " + (i + 2));
}
}
// Helper method to check if number is prime
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}Pattern Programming
Star Patterns:
1. Right Triangle Pattern:
// Pattern:
// *
// **
// ***
// ****
// *****
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}2. Inverted Triangle Pattern:
// Pattern:
// *****
// ****
// ***
// **
// *
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}Number Patterns:
1. Number Triangle:
// Pattern:
// 1
// 12
// 123
// 1234
// 12345
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}2. Pascal's Triangle (first 6 rows):
// Pattern:
// 1
// 1 1
// 1 2 1
// 1 3 3 1
// 1 4 6 4 1
int n = 5;
for (int i = 0; i < n; i++) {
// Print spaces
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
// Calculate and print Pascal's triangle values
int val = 1;
for (int j = 0; j <= i; j++) {
System.out.print(val + " ");
val = val * (i - j) / (j + 1);
}
System.out.println();
}Diamond Pattern:
int n = 5;
// Upper half (including middle)
for (int i = 1; i <= n; i++) {
// Print spaces
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// Print stars
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
// Lower half
for (int i = n - 1; i >= 1; i--) {
// Print spaces
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// Print stars
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}Loop Control Statements
break Statement:
Terminates the loop immediately and transfers control to the statement after the loop.
// Find first number divisible by 7
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
System.out.println("First number divisible by 7: " + i);
break; // Exit loop immediately
}
}
// Search in array
int[] numbers = {5, 12, 8, 21, 3, 15, 7};
int target = 21;
boolean found = false;
for (int num : numbers) {
if (num == target) {
System.out.println("Found " + target + " in the array!");
found = true;
break; // Stop searching once found
}
}
if (!found) {
System.out.println(target + " not found in array.");
}continue Statement:
Skips the rest of the current iteration and continues with the next iteration.
// Print only odd numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Odd number: " + i);
}
// Process only positive numbers
int[] values = {5, -2, 8, -1, 12, -7, 3};
for (int value : values) {
if (value < 0) {
continue; // Skip negative numbers
}
// Process positive numbers
System.out.println("Processing positive: " + value);
int square = value * value;
System.out.println("Square: " + square);
}Labeled break and continue:
// break with label - exit outer loop
outerLoop: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println("Breaking out of both loops at i=" + i + ", j=" + j);
break outerLoop; // Breaks out of the labeled loop
}
System.out.println("i=" + i + ", j=" + j);
}
}
// continue with label - continue outer loop
outerLoop: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 1) {
System.out.println("Continuing outer loop at i=" + i + ", j=" + j);
continue outerLoop; // Continues with next iteration of labeled loop
}
System.out.println("i=" + i + ", j=" + j);
}
}Loop Types Comparison
| Feature | for Loop | while Loop | do-while Loop | Enhanced for |
|---|---|---|---|---|
| Entry/Exit Control | Entry-controlled | Entry-controlled | Exit-controlled | Entry-controlled |
| Minimum Executions | 0 times | 0 times | 1 time | 0 times |
| Best Use Case | Known iterations | Unknown iterations | At least one execution | Array/Collection traversal |
| Initialization | In loop header | Before loop | Before loop | Automatic |
| Update | In loop header | In loop body | In loop body | Automatic |
Choosing the Right Loop:
- for loop: When you know the number of iterations (counting)
- while loop: When condition-based repetition is needed
- do-while loop: When you need at least one execution (menus, validation)
- enhanced for: When traversing arrays or collections
Previous Year Exam Questions
Q1. (GTU Summer 2022) Write a Java program to print the following pattern using nested loops:
* ** *** **** *****
Solution:
public class StarPattern {
public static void main(String[] args) {
int rows = 5;
// Method 1: Using nested for loops
System.out.println("Method 1: Using nested for loops");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println(); // Move to next line
}
// Method 2: Using while loops
System.out.println("\nMethod 2: Using while loops");
int i = 1;
while (i <= rows) {
int j = 1;
while (j <= i) {
System.out.print("*");
j++;
}
System.out.println();
i++;
}
// Method 3: Using String multiplication (alternative approach)
System.out.println("\nMethod 3: Using String repetition");
for (int k = 1; k <= rows; k++) {
String stars = "";
for (int m = 1; m <= k; m++) {
stars += "*";
}
System.out.println(stars);
}
}
}Q2. (GTU Winter 2021) Explain different types of loops in Java with examples. Write a program to find factorial of a number using any loop.
Solution:
Types of Loops in Java:
1. for Loop:
- Entry-controlled loop with initialization, condition, and update in header
- Best for known number of iterations
// Syntax: for(init; condition; update) { body }2. while Loop:
- Entry-controlled loop that checks condition before execution
- Used when number of iterations is unknown
// Syntax: while(condition) { body }3. do-while Loop:
- Exit-controlled loop that executes body at least once
- Condition checked after execution
// Syntax: do { body } while(condition);Factorial Program using different loops:
import java.util.Scanner;
public class FactorialProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
// Method 1: Using for loop
long factorial1 = 1;
for (int i = 1; i <= n; i++) {
factorial1 *= i;
}
System.out.println(n + "! using for loop = " + factorial1);
// Method 2: Using while loop
long factorial2 = 1;
int i = 1;
while (i <= n) {
factorial2 *= i;
i++;
}
System.out.println(n + "! using while loop = " + factorial2);
// Method 3: Using do-while loop
long factorial3 = 1;
int j = 1;
if (n > 0) {
do {
factorial3 *= j;
j++;
} while (j <= n);
}
System.out.println(n + "! using do-while loop = " + factorial3);
scanner.close();
}
}Q3. (GTU Summer 2020) Write a Java program to check whether a given number is prime or not using loops. Also find all prime numbers between 1 to 100.
Solution:
public class PrimeNumbers {
// Method to check if a number is prime
public static boolean isPrime(int number) {
if (number <= 1) {
return false; // Numbers <= 1 are not prime
}
if (number <= 3) {
return true; // 2 and 3 are prime
}
if (number % 2 == 0 || number % 3 == 0) {
return false; // Divisible by 2 or 3
}
// Check for factors from 5 to sqrt(number)
for (int i = 5; i * i <= number; i += 6) {
if (number % i == 0 || number % (i + 2) == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// Test specific numbers
int[] testNumbers = {17, 25, 29, 100, 97};
System.out.println("Prime Number Check:");
for (int num : testNumbers) {
if (isPrime(num)) {
System.out.println(num + " is a prime number");
} else {
System.out.println(num + " is not a prime number");
}
}
// Find all prime numbers between 1 and 100
System.out.println("\nPrime numbers between 1 and 100:");
int count = 0;
for (int i = 2; i <= 100; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
count++;
// Print 10 numbers per line for better formatting
if (count % 10 == 0) {
System.out.println();
}
}
}
System.out.println("\n\nTotal prime numbers between 1 and 100: " + count);
// Alternative method using basic trial division
System.out.println("\nAlternative method for checking prime:");
int numberToCheck = 29;
boolean isPrimeFlag = true;
if (numberToCheck <= 1) {
isPrimeFlag = false;
} else {
for (int i = 2; i <= numberToCheck / 2; i++) {
if (numberToCheck % i == 0) {
isPrimeFlag = false;
break; // No need to check further
}
}
}
if (isPrimeFlag) {
System.out.println(numberToCheck + " is prime");
} else {
System.out.println(numberToCheck + " is not prime");
}
}
}Hands-on Lab Exercises
Exercise 1: Number Series Calculator
- Write a program that calculates the sum of the following series using different loops:
- Sum of first n natural numbers: 1 + 2 + 3 + ... + n
- Sum of squares: 1² + 2² + 3² + ... + n²
- Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, ...
- Compare performance and readability of different loop types
Exercise 2: Pattern Programming Challenge
- Create programs to print these patterns:
- Hollow rectangle pattern
- Number pyramid pattern
- Diamond pattern with numbers
- Floyd's triangle
- Make the patterns size configurable through user input
Exercise 3: Interactive Menu System
- Create a comprehensive calculator with menu options:
- Basic arithmetic operations
- Advanced operations (power, factorial, GCD)
- Number system conversions
- Pattern generation
- Use do-while loop for menu repetition
- Implement input validation with while loops
Lecture Summary
Key Concepts Covered:
- for loop structure and applications
- while loop for condition-based iteration
- do-while loop for guaranteed execution
- Enhanced for loop for array traversal
- Nested loops and pattern programming
- Loop control statements (break, continue)
- Loop selection criteria and best practices
Learning Outcomes Achieved:
- ✅ Master all loop types and their syntax
- ✅ Apply appropriate loop for different scenarios
- ✅ Create complex nested loop structures
- ✅ Implement pattern programming algorithms
- ✅ Use loop control statements effectively
- ✅ Debug common loop-related errors
- ✅ Optimize loop performance and readability
Next Lecture: Arrays - 1D and 2D
Topics: Array declaration, initialization, manipulation, multidimensional arrays, array algorithms
Thank You!
Questions & Discussion
Next: Lecture 07 - Arrays (1D and 2D)
Course: 4343203 Java Programming
Unit 1: Introduction to Java
GTU Semester 4

