This set of 40 Java loop exercises is designed to build real comfort with for, while, and do-while loops, from the very first counting loop up to multi-level nested loops.
What You’ll Practice
- Fundamentals: Counting, accumulating sums and products, and digit extraction using the modulus and division operators.
- Number Logic: Primes, factors, GCD/LCM, Armstrong numbers, perfect numbers, and base conversions (binary/decimal).
- Patterns: Triangles, pyramids, diamonds, and Pascal’s and Floyd’s triangles using nested loops.
- Arrays & Matrices: Min/max search, reversing, sorting, duplicate detection, and matrix transposition and multiplication.
Each exercise includes a Practice Problem, Exercise Purpose, Hint, and a fully explained Solution, so you build the logic yourself before checking your approach against a working answer.
- Also, See: Java Exercises with over 20+ topic-wise sets and 575+ coding questions to practice.
- Practice questions using our Online Java Compiler
+ Table of Contents (40 Exercises)
Table of contents
- Exercise 1: Print Numbers from 1 to 10
- Exercise 2: Reverse Countdown
- Exercise 3: Even Numbers
- Exercise 4: Odd Numbers
- Exercise 5: Sum of Natural Numbers
- Exercise 6: Multiplication Table
- Exercise 7: Factorial Calculation
- Exercise 8: Count Digits
- Exercise 9: Sum of Digits
- Exercise 10: Reverse a Number
- Exercise 11: Prime Number Check
- Exercise 12: Fibonacci Series
- Exercise 13: Palindrome Number
- Exercise 14: Armstrong Number
- Exercise 15: Greatest Common Divisor (GCD)
- Exercise 16: Least Common Multiple (LCM)
- Exercise 17: Find All Factors
- Exercise 18: Binary to Decimal
- Exercise 19: Decimal to Binary
- Exercise 20: Power Calculation
- Exercise 21: Right Triangle Pattern
- Exercise 22: Inverted Right Triangle
- Exercise 23: Pyramid Pattern
- Exercise 24: Number Pyramid
- Exercise 25: Pascal’s Triangle
- Exercise 26: Array Min/Max
- Exercise 27: Array Reverse
- Exercise 28: Element Frequency
- Exercise 29: Check Sorted Array
- Exercise 30: Bubble Sort Implementation
- Exercise 31: Perfect Number Check
- Exercise 32: Strong Number Check
- Exercise 33: Harshad Number
- Exercise 34: Floyd’s Triangle
- Exercise 35: Diamond Pattern
- Exercise 36: Matrix Transpose
- Exercise 37: Matrix Multiplication
- Exercise 38: Find Second Largest Element
- Exercise 39: Remove Duplicates from Array
- Exercise 40: Number Guessing Game (do-while)
Exercise 1: Print Numbers from 1 to 10
Practice Problem: Write a program that prints all integers from 1 to 10 on a single line, separated by spaces.
Exercise purpose: To learn the fundamental syntax and control flow of a for loop, including loop initialization, the exit condition, and the increment step.
Given Input: (None)
Expected Output: 1 2 3 4 5 6 7 8 9 10
▼ Hint
- A for loop typically has three components:
for(initialization; condition; update). - Use
System.out.print()instead ofprintln()to keep everything on one line.
▼ Solution and Explanation:
Explanation:
int i = 1: Initializes the loop counter starting at 1.i <= 10: The loop continues as long as i is less than or equal to 10.i++: Increments the counter by 1 after each iteration.System.out.print(i + " "): Prints the current value of i followed by a space, keeping all numbers on one line.
Exercise 2: Reverse Countdown
Practice Problem: Write a program that prints numbers from 10 down to 1 using a while loop.
Exercise purpose: To practice using a while loop with a decrementing counter, and to understand how the loop condition is checked before each iteration.
Given Input: (None)
Expected Output: 10 9 8 7 6 5 4 3 2 1
▼ Hint
- A while loop checks its condition before each iteration and keeps running until the condition becomes false.
- Decrement the counter using
i--inside the loop body so the loop eventually ends.
▼ Solution and Explanation:
Explanation:
int i = 10: Initializes the counter at 10, the starting point of the countdown.while (i >= 1): The loop runs as long as i is greater than or equal to 1.System.out.print(i + " "): Prints the current value of i on the same line.i--: Decreases i by 1 after each print, moving the countdown forward.
Exercise 3: Even Numbers
Practice Problem: Write a program that prints all even numbers between 1 and 50.
Exercise purpose: To combine a for loop with a conditional check, and to practice using the modulus operator to test divisibility.
Given Input: (None)
Expected Output: 2 4 6 8 … 48 50
▼ Hint
- Use the modulus operator
%to check if a number is divisible by 2. - Loop through 1 to 50 and print only the numbers where
number % 2 == 0.
▼ Solution and Explanation:
Explanation:
for (int i = 1; i <= 50; i++): Loops through every integer from 1 to 50.i % 2 == 0: Checks whether i is evenly divisible by 2, which identifies even numbers.System.out.print(i + " "): Prints the number if it passes the even check.
Exercise 4: Odd Numbers
Practice Problem: Write a program that prints all odd numbers between 1 and 50.
Exercise purpose: To reinforce the use of conditional checks inside a loop, this time testing for numbers that are not evenly divisible by 2.
Given Input: (None)
Expected Output: 1 3 5 7 … 47 49
▼ Hint
- Use the modulus operator
%to check if a number is not divisible by 2. - Loop through 1 to 50 and print only the numbers where
number % 2 != 0.
▼ Solution and Explanation:
Explanation:
for (int i = 1; i <= 50; i++): Iterates through all integers from 1 to 50.i % 2 != 0: Checks whether i leaves a remainder when divided by 2, which identifies odd numbers.System.out.print(i + " "): Prints the number if it passes the odd check.
Exercise 5: Sum of Natural Numbers
Practice Problem: Write a program that calculates and prints the sum of the first 10 natural numbers (1 + 2 + … + 10).
Exercise purpose: To practice accumulating a value across loop iterations using a running total variable.
Given Input: (None)
Expected Output: Sum = 55
▼ Hint
- Declare a variable to hold the running total before the loop starts, and set it to 0.
- Add the loop counter to the total during each iteration.
▼ Solution and Explanation:
Explanation:
int sum = 0: Initializes a variable to store the running total, starting at 0.for (int i = 1; i <= 10; i++): Loops through the numbers 1 to 10.sum += i: Adds the current value of i to sum during each iteration.System.out.println("Sum = " + sum): Prints the final total after the loop finishes.
Exercise 6: Multiplication Table
Practice Problem: Write a program that asks the user for an integer N and prints its multiplication table up to 10.
Exercise purpose: To practice reading user input with Scanner and using that input as a fixed value inside a loop.
Given Input: N = 7
Expected Output:
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
▼ Hint
- Use a
Scannerobject to read the integer input from the user. - Loop from 1 to 10 and multiply the input number by the loop counter during each iteration.
▼ Solution and Explanation:
Explanation:
Scanner scanner = new Scanner(System.in): Creates a Scanner object to read input from the console.int num = scanner.nextInt(): Reads the integer entered by the user and stores it in num.for (int i = 1; i <= 10; i++): Loops exactly 10 times, from i = 1 to i = 10.num * i: Multiplies the input number by the current loop counter to get the product.
Exercise 7: Factorial Calculation
Practice Problem: Write a program that finds the factorial of a given number n (for example, 5! = 5 x 4 x 3 x 2 x 1).
Exercise purpose: To practice building a running product across loop iterations, and to understand why the accumulator must start at 1 rather than 0.
Given Input: n = 5
Expected Output: 5! = 120
▼ Hint
- Initialize a variable to 1 to hold the running product, since starting at 0 would make every result 0.
- Multiply the result by the loop counter during each iteration.
▼ Solution and Explanation:
Explanation:
long factorial = 1: Initializes the result variable to 1, since multiplying by 0 would always give 0.for (int i = 1; i <= n; i++): Loops from 1 up to n, the number whose factorial is being calculated.factorial *= i: Multiplies the running result by the current loop counter during each iteration.System.out.println(n + "! = " + factorial): Prints the final factorial value once the loop completes.
Exercise 8: Count Digits
Practice Problem: Take an integer input from the user and count how many digits it has using a while loop.
Exercise purpose: To practice stripping digits off a number with integer division, and to use a counter variable to track how many times the loop runs.
Given Input: number = 12345
Expected Output: Number of digits = 5
▼ Hint
- Use the division operator
/to remove the last digit of the number during each iteration. - Use a counter variable that increases by 1 every time a digit is removed.
▼ Solution and Explanation:
Explanation:
int temp = number: Copies the original number into a temporary variable so the original value stays unchanged.while (temp != 0): Continues looping until all digits have been removed.temp = temp / 10: Removes the last digit of temp using integer division.count++: Increases the digit counter by 1 during each iteration.
Exercise 9: Sum of Digits
Practice Problem: Take an integer input and calculate the sum of its digits (for example, if the input is 345, the sum is 3 + 4 + 5 = 12).
Exercise purpose: To combine the modulus and division operators to extract and accumulate individual digits of a number.
Given Input: number = 345
Expected Output: Sum of digits = 12
▼ Hint
- Use the modulus operator
%to extract the last digit of the number. - Use the division operator
/to remove the last digit after extracting it.
▼ Solution and Explanation:
Explanation:
int digit = temp % 10: Extracts the last digit of temp using the modulus operator.sum += digit: Adds the extracted digit to the running total.temp = temp / 10: Removes the last digit from temp so the next iteration can process the remaining digits.while (temp != 0): Continues the process until every digit has been processed.
Exercise 10: Reverse a Number
Practice Problem: Input an integer and reverse its digits (for example, 1234 becomes 4321).
Exercise purpose: To practice building a new number digit by digit while stripping digits off the original, reinforcing the modulus and division pattern used in previous exercises.
Given Input: number = 1234
Expected Output: Reversed number = 4321
▼ Hint
- Extract the last digit using the modulus operator
%, then build the reversed number by shifting its existing digits left before adding the new one. - Use the division operator
/to remove the last digit after extracting it, just like in the digit counting and digit sum exercises.
▼ Solution and Explanation:
Explanation:
int digit = temp % 10: Extracts the last digit of temp.reversed = reversed * 10 + digit: Shifts the digits already in reversed one place to the left, then adds the new digit.temp = temp / 10: Removes the last digit from temp so the loop can process the next one.while (temp != 0): Repeats the process until all digits have been reversed.
Exercise 11: Prime Number Check
Practice Problem: Write a program that determines whether a given number is prime or not.
Exercise purpose: To practice looping with a conditional check, and to learn how limiting the loop range up to the square root of a number makes the check more efficient.
Given Input: number = 29
Expected Output: 29 is a prime number
▼ Hint
- A number is prime if it has no divisors other than 1 and itself.
- Loop from 2 up to the square root of the number and check for any divisor.
▼ Solution and Explanation:
Explanation:
boolean isPrime = true: Assumes the number is prime until a divisor proves otherwise.for (int i = 2; i <= Math.sqrt(number); i++): Only checks divisors up to the square root of the number, since checking further is redundant.number % i == 0: Checks if i divides evenly into number.break: Exits the loop immediately once a divisor is found, since there’s no need to keep checking.
Exercise 12: Fibonacci Series
Practice Problem: Print the first N terms of the Fibonacci series (0, 1, 1, 2, 3, 5, 8, …), where N is provided by the user.
Exercise purpose: To practice tracking multiple state variables across loop iterations, where each new value depends on the two values before it.
Given Input: N = 8
Expected Output: 0 1 1 2 3 5 8 13
▼ Hint
- Keep track of the two previous terms and add them together to get the next term.
- Print the current term before updating the two tracking variables for the next iteration.
▼ Solution and Explanation:
Explanation:
int first = 0, second = 1: Initializes the first two terms of the series.System.out.print(first + " "): Prints the current term before updating the values.int next = first + second: Calculates the next term by adding the two previous terms.first = second; second = next;: Shifts both variables forward by one position for the next iteration.
Exercise 13: Palindrome Number
Practice Problem: Check if a given number is a palindrome (reads the same backward as forward, like 121 or 4554).
Exercise purpose: To reuse the digit-reversal technique from earlier exercises and apply it to solve a comparison based problem.
Given Input: number = 121
Expected Output: 121 is a palindrome
▼ Hint
- Reverse the number using the same digit-by-digit technique from the Reverse a Number exercise.
- Compare the reversed number to the original to check if they match.
▼ Solution and Explanation:
Explanation:
int temp = number: Preserves the original number while temp is broken down digit by digit.while (temp != 0): Repeats until every digit has been processed.reversed = reversed * 10 + digit: Builds the reversed number one digit at a time.number == reversed: Compares the original number to its reversed version to determine if it’s a palindrome.
Exercise 14: Armstrong Number
Practice Problem: Check if a 3-digit number is an Armstrong number (the sum of the cubes of its digits equals the number itself, e.g., 153 = 13 + 53 + 33).
Exercise purpose: To combine digit extraction with an accumulated calculation, then compare the result back against the original number.
Given Input: number = 153
Expected Output: 153 is an Armstrong number
▼ Hint
- Extract each digit using the modulus operator, then cube it and add it to a running total.
- Compare the running total to the original number once all digits have been processed.
▼ Solution and Explanation:
Explanation:
int digit = temp % 10: Extracts the last digit of temp.sum += digit * digit * digit: Cubes the digit and adds it to the running total.temp = temp / 10: Removes the last digit so the loop can process the next one.sum == number: Checks whether the sum of the cubed digits equals the original number.
Exercise 15: Greatest Common Divisor (GCD)
Practice Problem: Find the GCD (Highest Common Factor) of two numbers using a loop.
Exercise purpose: To practice checking multiple numbers against two conditions at once, and to track the best result found so far during a loop.
Given Input: a = 48, b = 18
Expected Output: GCD = 6
▼ Hint
- Loop from 1 up to the smaller of the two numbers, since the GCD can never be larger than the smaller number.
- Keep track of the largest value found so far that divides both numbers evenly.
▼ Solution and Explanation:
Explanation:
int smaller = (a < b) ? a : b: Determines the smaller of the two numbers, since the GCD cannot be larger than that.for (int i = 1; i <= smaller; i++): Checks every number from 1 up to the smaller value.a % i == 0 && b % i == 0: Confirms that i divides both a and b evenly.gcd = i: Updates the GCD each time a larger common divisor is found.
Exercise 16: Least Common Multiple (LCM)
Practice Problem: Find the LCM of two numbers using loops and the GCD relationship.
Exercise purpose: To reuse the GCD loop from the previous exercise and apply the mathematical relationship between GCD and LCM to solve a new problem.
Given Input: a = 4, b = 6
Expected Output: LCM = 12
▼ Hint
- The LCM of two numbers can be calculated as (a * b) / GCD(a, b).
- Reuse the GCD logic from the previous exercise before applying the LCM formula.
▼ Solution and Explanation:
Explanation:
for (int i = 1; i <= smaller; i++): Loops through possible divisors to find the GCD of a and b, the same approach used in the GCD exercise.gcd = i: Stores the largest common divisor found during the loop.int lcm = (a * b) / gcd: Applies the relationship between LCM and GCD to calculate the least common multiple.System.out.println("LCM = " + lcm): Prints the final result.
Exercise 17: Find All Factors
Practice Problem: Print all the factors of a given number (e.g., factors of 12 are 1, 2, 3, 4, 6, 12).
Exercise purpose: To practice a straightforward divisibility check across a full range of numbers, reinforcing the modulus operator’s role in identifying factors.
Given Input: number = 12
Expected Output: 1 2 3 4 6 12
▼ Hint
- Loop through every number from 1 to the given number.
- Use the modulus operator to check if each number divides evenly into the given number.
▼ Solution and Explanation:
Explanation:
for (int i = 1; i <= number; i++): Checks every integer from 1 up to the number itself.number % i == 0: Confirms that i divides evenly into number, making it a factor.System.out.print(i + " "): Prints each factor as it’s found, keeping them on one line.
Exercise 18: Binary to Decimal
Practice Problem: Convert a binary number (entered as an integer containing only 0s and 1s) into its decimal equivalent using a loop.
Exercise purpose: To practice extracting digits from a number while tracking a positional power, and to apply that power in a running calculation.
Given Input: binary = 1101
Expected Output: Decimal = 13
▼ Hint
- Extract the last digit of the binary number using the modulus operator.
- Multiply each digit by the appropriate power of 2 based on its position, then add it to a running total.
▼ Solution and Explanation:
Explanation:
int lastDigit = binary % 10: Extracts the last digit (0 or 1) of the binary number.decimal += lastDigit * Math.pow(2, power): Multiplies the digit by 2 raised to its positional power and adds it to the running total.binary = binary / 10: Removes the last digit so the loop can process the next one.power++: Increases the power of 2 for the next digit’s position.
Exercise 19: Decimal to Binary
Practice Problem: Convert a decimal number into its binary string equivalent using a loop.
Exercise purpose: To practice building a result string by repeatedly dividing a number and prepending each remainder, the reverse process of the previous exercise.
Given Input: decimal = 13
Expected Output: Binary = 1101
▼ Hint
- Repeatedly divide the number by 2 and record the remainder at each step.
- Since the remainders are generated in reverse order, build the binary string by placing each new remainder before the previous ones.
▼ Solution and Explanation:
Explanation:
int remainder = decimal % 2: Finds the remainder when the number is divided by 2, which is either 0 or 1.binary = remainder + binary: Adds the new remainder to the front of the binary string, since remainders are produced from least significant to most significant bit.decimal = decimal / 2: Divides the number by 2 to prepare for finding the next bit.while (decimal > 0): Continues until the number has been fully divided down to 0.
Exercise 20: Power Calculation
Practice Problem: Write a program to calculate the value of x raised to the power of y (x^y) without using Java’s built-in Math.pow() function.
Exercise purpose: To practice implementing repeated multiplication manually using a loop, reinforcing how exponentiation works under the hood.
Given Input: x = 2, y = 5
Expected Output: 2^5 = 32
▼ Hint
- Initialize a result variable to 1, then multiply it by x a total of y times using a loop.
- Avoid using
Math.pow(), since the purpose of this exercise is to implement the logic manually.
▼ Solution and Explanation:
Explanation:
long result = 1: Initializes the result to 1, since multiplying by 1 doesn’t change the starting value.for (int i = 1; i <= y; i++): Loops exactly y times, once for each multiplication by x.result *= x: Multiplies the running result by x during each iteration.System.out.println(x + "^" + y + " = " + result): Prints the final calculated power.
Exercise 21: Right Triangle Pattern
Practice Problem: Use nested loops to print a right-angled triangle of stars (*).
Exercise purpose: To introduce nested loops, where an outer loop controls the rows and an inner loop controls what gets printed within each row.
Given Input: rows = 5
Expected Output:
*
**
***
****
*****
▼ Hint
- Use an outer loop to control the number of rows.
- Use an inner loop to print the correct number of stars on each row, based on the current row number.
▼ Solution and Explanation:
Explanation:
for (int i = 1; i <= rows; i++): The outer loop controls how many rows are printed.for (int j = 1; j <= i; j++): The inner loop prints stars for the current row; since j goes up to i, each row has one more star than the last.System.out.println(): Moves to a new line after each row is finished.
Exercise 22: Inverted Right Triangle
Practice Problem: Use nested loops to print an inverted right-angled triangle of stars.
Exercise purpose: To practice controlling a nested loop with a decrementing outer counter, reversing the pattern built in the previous exercise.
Given Input: rows = 5
Expected Output:
*****
****
***
**
*
▼ Hint
- Use an outer loop that counts down from the total number of rows.
- Use an inner loop to print stars based on the current value of the outer loop’s counter.
▼ Solution and Explanation:
Explanation:
for (int i = rows; i >= 1; i--): The outer loop starts at the total number of rows and counts down to 1.for (int j = 1; j <= i; j++): The inner loop prints stars based on i, so the number of stars decreases as i decreases.System.out.println(): Starts a new line after each row.
Exercise 23: Pyramid Pattern
Practice Problem: Use nested loops to print a centered pyramid of stars.
Exercise purpose: To practice using two inner loops within a single outer loop, one to print leading spaces and one to print the pattern itself.
Given Input: rows = 5
Expected Output:
*
***
*****
*******
*********
▼ Hint
- Each row needs a combination of leading spaces and stars; use one inner loop for the spaces and another for the stars.
- The number of spaces decreases and the number of stars increases by 2 with each row.
▼ Solution and Explanation:
Explanation:
for (int j = 1; j <= rows - i; j++): Prints the leading spaces needed to center the row, which decreases as i increases.for (int k = 1; k <= (2 * i - 1); k++): Prints an odd number of stars for each row, based on the formula 2i – 1.System.out.println(): Moves to the next row after both inner loops complete.
Exercise 24: Number Pyramid
Practice Problem: Print a pyramid pattern using numbers instead of stars.
Exercise purpose: To adapt the nested loop pattern from earlier exercises to print sequential values instead of a fixed symbol.
Given Input: rows = 5
Expected Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
▼ Hint
- Use a nested loop, where the inner loop prints numbers from 1 up to the current row number.
- Add a space after each printed number to separate them.
▼ Solution and Explanation:
Explanation:
for (int i = 1; i <= rows; i++): The outer loop controls the row number.for (int j = 1; j <= i; j++): The inner loop prints numbers from 1 up to the current row number i.System.out.println(): Starts a new line once a row’s numbers are printed.
Exercise 25: Pascal’s Triangle
Practice Problem: Print Pascal’s Triangle up to N rows using nested loops.
Exercise purpose: To practice calculating each value in a row from the one before it, rather than recalculating factorials from scratch for every position.
Given Input: N = 5
Expected Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
▼ Hint
- Each value in the triangle can be calculated from the previous value using the formula
value * (row - column) / (column + 1). - Use a nested loop, where the outer loop handles rows and the inner loop calculates and prints each value in that row.
▼ Solution and Explanation:
Explanation:
for (int i = 0; i < rows; i++): The outer loop controls which row of the triangle is being built.int value = 1: Each row starts with a value of 1, since the first number in every row of Pascal’s Triangle is always 1.value = value * (i - j) / (j + 1): Calculates the next value in the row using the relationship between binomial coefficients, avoiding the need to calculate factorials directly.System.out.println(): Moves to the next row after the current one is complete.
Exercise 26: Array Min/Max
Practice Problem: Create an array of integers and use a loop to find both the maximum and minimum elements.
Exercise purpose: To practice iterating through an array while tracking two running values at once.
Given Input: numbers = {12, 45, 2, 89, 33}
Expected Output: Max = 89, Min = 2
▼ Hint
- Initialize both the max and min variables to the first element of the array before looping.
- Compare each element to the current max and min, updating them whenever a larger or smaller value is found.
▼ Solution and Explanation:
Explanation:
int max = numbers[0]; int min = numbers[0];: Starts both max and min at the first element, giving the loop a baseline to compare against.for (int i = 1; i < numbers.length; i++): Loops through the remaining elements, starting at index 1 since index 0 is already accounted for.if (numbers[i] > max): Updates max whenever a larger element is found.if (numbers[i] < min): Updates min whenever a smaller element is found.
Exercise 27: Array Reverse
Practice Problem: Reverse the elements of an array in place using a loop (e.g., [1, 2, 3] becomes [3, 2, 1]).
Exercise purpose: To practice the two-pointer technique, where two indices move toward each other from opposite ends of an array.
Given Input: numbers = {1, 2, 3, 4, 5}
Expected Output: 5 4 3 2 1
▼ Hint
- Use two index pointers, one starting at the beginning of the array and one at the end, and swap the elements they point to.
- Move the pointers toward each other after each swap, stopping once they meet in the middle.
▼ Solution and Explanation:
Explanation:
int start = 0; int end = numbers.length - 1;: Sets up two pointers, one at each end of the array.while (start < end): Continues swapping until the pointers meet or cross in the middle.int temp = numbers[start]: Uses a temporary variable to swap the elements at the start and end positions without losing either value.start++; end--;: Moves the pointers closer together after each swap.
Exercise 28: Element Frequency
Practice Problem: Count how many times a specific element appears in an array using a loop.
Exercise purpose: To practice using a counter variable alongside a loop condition to tally matches within a collection of values.
Given Input: numbers = {2, 4, 2, 5, 2, 7}, target = 2
Expected Output: 2 appears 3 times
▼ Hint
- Use a counter variable to track how many times the target value is found.
- Loop through the array and increment the counter whenever the current element matches the target.
▼ Solution and Explanation:
Explanation:
int count = 0: Initializes a counter to track how many matches are found.for (int i = 0; i < numbers.length; i++): Loops through every element in the array.numbers[i] == target: Checks whether the current element matches the target value.count++: Increases the counter each time a match is found.
Exercise 29: Check Sorted Array
Practice Problem: Write a loop to check if an array of integers is sorted in ascending order.
Exercise purpose: To practice comparing adjacent elements in a single pass and exiting early once a condition is proven false.
Given Input: numbers = {3, 8, 15, 22, 40}
Expected Output: The array is sorted in ascending order
▼ Hint
- Loop through the array and compare each element to the one that follows it.
- If any element is greater than the one after it, the array is not sorted.
▼ Solution and Explanation:
Explanation:
boolean isSorted = true: Assumes the array is sorted until proven otherwise.for (int i = 0; i < numbers.length - 1; i++): Loops up to the second-to-last element, since each element is compared to the one after it.numbers[i] > numbers[i + 1]: Checks if the current element is greater than the next one, which would break the ascending order.break: Stops checking as soon as an out-of-order pair is found, since the array is already known not to be sorted.
Exercise 30: Bubble Sort Implementation
Practice Problem: Use nested loops to implement the Bubble Sort algorithm to sort an array of integers.
Exercise purpose: To combine nested loops, conditional checks, and element swapping into a complete sorting algorithm.
Given Input: numbers = {5, 2, 9, 1, 5, 6}
Expected Output: 1 2 5 5 6 9
▼ Hint
- Use a nested loop, where the outer loop controls the number of passes and the inner loop compares adjacent elements.
- Swap two adjacent elements whenever the first is greater than the second.
▼ Solution and Explanation:
Explanation:
for (int i = 0; i < numbers.length - 1; i++): The outer loop controls how many passes are made through the array.for (int j = 0; j < numbers.length - 1 - i; j++): The inner loop compares adjacent elements; the range shrinks each pass since the largest elements are already sorted to the end.numbers[j] > numbers[j + 1]: Checks if two adjacent elements are out of order.int temp = numbers[j]: Swaps the two elements using a temporary variable if they’re out of order.
Exercise 31: Perfect Number Check
Practice Problem: Write a program to check if a given number is a Perfect Number. A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself (e.g., 6 = 1 + 2 + 3).
Exercise purpose: To practice summing divisors found during a loop and comparing that sum against the original value.
Given Input: number = 6
Expected Output: 6 is a Perfect Number
▼ Hint
- Loop from 1 to number – 1 and check which values divide the number evenly.
- Add up all the divisors found and compare the sum to the original number.
▼ Solution and Explanation:
Explanation:
for (int i = 1; i < number; i++): Loops through every number less than the original number, since a perfect number excludes itself from its divisors.number % i == 0: Checks if i is a divisor of number.sum += i: Adds each divisor found to a running total.sum == number: Compares the total of the divisors to the original number to determine if it’s perfect.
Exercise 32: Strong Number Check
Practice Problem: Check if a number is a Strong Number. A number is called a strong number if the sum of the factorials of its digits is equal to the number itself (e.g., 145 = 1! + 4! + 5!).
Exercise purpose: To practice nesting a factorial calculation inside a digit-extraction loop.
Given Input: number = 145
Expected Output: 145 is a Strong Number
▼ Hint
- Extract each digit and calculate its factorial using a small inner loop.
- Add the factorial of each digit to a running total, then compare it to the original number.
▼ Solution and Explanation:
Explanation:
int digit = temp % 10: Extracts the last digit of temp during each iteration.for (int i = 1; i <= digit; i++): An inner loop calculates the factorial of the current digit.sum += factorial: Adds the digit’s factorial to the running total.sum == number: Checks whether the sum of all the digit factorials equals the original number.
Exercise 33: Harshad Number
Practice Problem: Determine if a number is a Harshad Number (or Niven number), which is an integer that is divisible by the sum of its digits (e.g., 18 is divisible by 1 + 8 = 9).
Exercise purpose: To combine digit-sum calculation with a divisibility check, reinforcing patterns used in earlier digit-based exercises.
Given Input: number = 18
Expected Output: 18 is a Harshad Number
▼ Hint
- Calculate the sum of the digits of the number using the modulus and division operators.
- Check if the original number is evenly divisible by that digit sum.
▼ Solution and Explanation:
Explanation:
digitSum += temp % 10: Adds each extracted digit to a running total that tracks the sum of all digits.temp = temp / 10: Removes the last digit so the loop can process the next one.number % digitSum == 0: Checks whether the original number is evenly divisible by the sum of its digits.
Exercise 34: Floyd’s Triangle
Practice Problem: Use nested loops to print Floyd’s Triangle up to N rows.
Exercise purpose: To practice using a single counter that increases continuously across all rows, rather than resetting at the start of each row.
Given Input: rows = 5
Expected Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
▼ Hint
- Use a single counter variable that keeps increasing across the entire triangle, rather than resetting at the start of every row.
- Use a nested loop, where the inner loop prints as many numbers as the current row number.
▼ Solution and Explanation:
Explanation:
int number = 1: Initializes a single counter that will be used across the entire triangle, not just within a row.for (int j = 1; j <= i; j++): The inner loop prints as many numbers as the current row requires.number++: Increases the counter after every number printed, so it keeps climbing across all rows.System.out.println(): Starts a new line once a row is complete.
Exercise 35: Diamond Pattern
Practice Problem: Print a full diamond star pattern using nested loops.
Exercise purpose: To combine two nested loop patterns, an upper pyramid and an inverted lower pyramid, into a single continuous shape.
Given Input: rows = 5
Expected Output:
*
***
*****
*******
*********
*******
*****
***
*
▼ Hint
- Build the diamond by printing an upper pyramid first, then a lower inverted pyramid directly beneath it.
- Reuse the space-and-star logic from the Pyramid Pattern exercise for both halves.
▼ Solution and Explanation:
Explanation:
- The first nested loop builds the upper half of the diamond, using the same space-and-star logic as the Pyramid Pattern exercise.
for (int i = rows - 1; i >= 1; i--): The second outer loop starts one row below the widest point and counts down, forming the lower half.- The inner loops in the second block mirror the first, printing fewer stars and more spaces as i decreases.
System.out.println(): Moves to the next row after each row of the diamond is printed.
Exercise 36: Matrix Transpose
Practice Problem: Given a 2D array (matrix), use nested loops to find and print its transpose (swapping rows and columns).
Exercise purpose: To practice working with two-dimensional arrays, and to understand how swapping row and column indices transposes a matrix.
Given Input: matrix = {{1, 2, 3}, {4, 5, 6}}
Expected Output:
1 4
2 5
3 6
▼ Hint
- Use nested loops to iterate through every row and column of the original matrix.
- Place each element at position [row][col] into a new matrix at position [col][row].
▼ Solution and Explanation:
Explanation:
int[][] transposed = new int[cols][rows]: Creates a new matrix with the number of rows and columns swapped compared to the original.transposed[j][i] = matrix[i][j]: Places each element from the original matrix into its swapped position in the new matrix.- The final nested loop prints the transposed matrix row by row.
Exercise 37: Matrix Multiplication
Practice Problem: Write a program that multiplies two 2D arrays (matrices) using nested loops. Remember to validate if the multiplication is possible based on dimensions.
Exercise purpose: To practice using three nested loops together, and to validate matrix dimensions before performing a calculation.
Given Input: matrixA = {{1, 2}, {3, 4}}, matrixB = {{5, 6}, {7, 8}}
Expected Output:
19 22
43 50
▼ Hint
- Multiplication is only possible if the number of columns in the first matrix matches the number of rows in the second matrix.
- Use three nested loops: two for the position in the result matrix, and one to calculate the sum of products for that position.
▼ Solution and Explanation:
Explanation:
if (colsA != rowsB): Validates that the multiplication is mathematically possible before proceeding.- The outer two loops (i and j) move through each position of the result matrix.
for (int k = 0; k < colsA; k++): The innermost loop calculates the sum of products needed for each position in the result matrix.result[i][j] += matrixA[i][k] * matrixB[k][j]: Accumulates the dot product of the corresponding row and column.
Exercise 38: Find Second Largest Element
Practice Problem: Write a loop to find the second largest number in a single-dimensional array without sorting it first.
Exercise purpose: To practice tracking two related running values in a single pass, updating both correctly whenever a new maximum is found.
Given Input: numbers = {12, 45, 2, 89, 33}
Expected Output: Second largest = 45
▼ Hint
- Track both the largest and second largest values as you loop through the array, rather than sorting it.
- When a new largest value is found, the old largest becomes the new second largest.
▼ Solution and Explanation:
Explanation:
int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE;: Starts both trackers as low as possible so any real value in the array will replace them.if (numbers[i] > largest): When a new largest value is found, the previous largest becomes the second largest before updating largest.else if (numbers[i] > secondLargest && numbers[i] != largest): Updates secondLargest if the current element isn’t the largest but is still bigger than the current second largest.- This single-pass approach finds both values without needing to sort the array.
Exercise 39: Remove Duplicates from Array
Practice Problem: Write a program using loops to remove duplicate elements from an array and compress the remaining elements.
Exercise purpose: To practice using a nested loop to check for existing matches before adding a new element, and to build a compressed result using a separate counter.
Given Input: numbers = {2, 4, 2, 5, 4, 7}
Expected Output: 2 4 5 7
▼ Hint
- Use one loop to walk through the array and a nested loop to check if the current element has already appeared earlier in the result.
- Keep a separate counter to track how many unique elements have been placed so far.
▼ Solution and Explanation:
Explanation:
int[] result = new int[numbers.length]; int uniqueCount = 0;: Creates an array to hold unique values and a counter to track how many have been added so far.for (int j = 0; j < uniqueCount; j++): The inner loop checks whether the current element already exists among the unique values found so far.isDuplicate = true; break;: Marks the element as a duplicate and stops checking once a match is found.if (!isDuplicate): Adds the element to the result array only if it hasn’t appeared before, then increases uniqueCount.
Exercise 40: Number Guessing Game (do-while)
Practice Problem: Generate a random number between 1 and 100. Use a do-while loop to repeatedly prompt the user to guess the number, giving hints like “Too high” or “Too low” until they guess correctly.
Exercise purpose: To learn the do-while loop structure, which is useful whenever the loop body needs to run at least once before its condition is checked.
Given Input: A randomly generated target number between 1 and 100, with guesses entered by the user, for example 70, then 30, then 42.
Expected Output:
Too high
Too low
Correct! You guessed it in 3 tries.
▼ Hint
- A do-while loop is useful here because the user needs to guess at least once before the condition is checked.
- Compare the guess to the target and print “Too high” or “Too low” accordingly, looping until the guess matches.
▼ Solution and Explanation:
Explanation:
int target = random.nextInt(100) + 1: Generates a random secret number between 1 and 100.do { ... } while (guess != target): A do-while loop runs the guessing logic at least once before checking whether the loop should continue.guess > target/guess < target: Compares the user’s guess to the target and prints a hint accordingly.attempts++: Tracks how many guesses the user has made, used in the final success message.

Leave a Reply