Course: 4343203 - Java Programming
GTU Semester 4 | Unit 1
Learning Objectives:
Loop Statements allow repeated execution of a block of code as long as a specified condition remains true.
for (initialization; condition; update) {
// loop body
}
// Components breakdown:
// 1. initialization - executed once
// 2. condition - checked before each iteration
// 3. update - executed after each iteration
// 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);
}
// 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); // 120
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 unknown
// 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!");
}
// 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 {
// 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!
// 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);
// 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.");
// 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);
}
// 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);
// 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");
// 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:
// 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);
}
}
// 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);
}
}
// 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();
}
// 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:
// *
// **
// ***
// ****
// *****
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
// Pattern:
// *****
// ****
// ***
// **
// *
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
// 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();
}
// 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();
}
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();
}
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.");
}
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);
}
// 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);
}
}
| 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:
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:
// Syntax: for(init; condition; update) { body }
// Syntax: while(condition) { body }
// Syntax: do { body } while(condition);
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");
}
}
}
Next Lecture: Arrays - 1D and 2D
Topics: Array declaration, initialization, manipulation, multidimensional arrays, array algorithms
Next: Lecture 07 - Arrays (1D and 2D)
Course: 4343203 Java Programming
Unit 1: Introduction to Java
GTU Semester 4