Java Loops Laboratory Activities
I. Fundamentals of Loops in Java
In Java, loops allow you to repeat a block of code multiple times. There are three primary loop
types:
1. for Loop
● Used when the number of iterations is known.
Syntax:
for(initialization; condition; update) {
// code to be executed
}
Example:
for(int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
2. while Loop
● Used when the number of iterations is not known in advance.
Syntax:
while(condition) {
// code to be executed
}
Example:
int i = 1;
while(i <= 5) {
[Link]("Count: " + i);
i++;
}
3. do-while Loop
● Similar to while but executes at least once, even if the condition is false.
Syntax:
do {
// code to be executed
} while(condition);
Example:
int i = 1;
do {
[Link]("Count: " + i);
i++;
} while(i <= 5);
II. Lab Activities
Activity 1: Multiplication Table Generator (for loop)
Write a program that asks the user for a number (integer) and prints its multiplication table from
1 to 10.
Sample Input/Output:
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
Activity 2: Sum of Natural Numbers (while loop)
Ask the user for an integer N. Using a while loop, calculate and display the sum of numbers
from 1 to N.
Sample Input/Output:
Enter a number: 10
Sum = 55
Activity 3: Factorial Calculator (do-while loop)
Ask the user for an integer N and compute the factorial (N!) using a do-while loop.
Sample Input/Output:
Enter a number: 5
Factorial = 120
Activity 4: Even and Odd Numbers (for loop)
Ask the user for a number N. Using a loop, print all even and odd numbers from 1 to N
separately.
Sample Input/Output:
Enter a number: 10
Even numbers: 2 4 6 8 10
Odd numbers: 1 3 5 7 9
Activity 5: Reverse Digits of a Number (while loop)
Ask the user to enter an integer. Using a while loop, reverse the digits and print the result.
Sample Input/Output:
Enter a number: 12345
Reversed: 54321
III. Submission Instructions
1. Create a single Java file named [Link].
2. Implement all 5 activities in the same file (separated by methods) or not.
3. Upload your project to GitHub.
4. Submit your GitHub repository link to the instructor.