Loops in Java – A Beginner-Friendly Guide
In our previous Python blog, we explored how loops make repetitive tasks easier. Now, let’s dive into the world of loops in Java — a powerful concept that helps us write cleaner, more efficient code.
In Java, we commonly use the following three types of loops:
-
for loop
-
while loop
-
do-while loop
Let’s begin with the most commonly used one — the for loop.
✅ What is a For Loop?
Imagine I ask you to print Hello Java 1000 times.
Would you really write:
import java.util.*;
public class Main{
public static void main(String[]args){
System.out.println("hello java");
System.out.println("hello java");
System.out.println("hello java");
}
}
😅 Definitely not, right?
That’s where for loops come in. Instead of repeating the same line of code again and again, we can use a loop to automate the repetition.
Here’s how a for loop works in Java:
Syntax:
for loop?programme:
import java.util.*;
public class Main{
public static void main(String[]args){
for (int counter=0;counter<11;counter++){
System.out.println(counter);
}
}
}
counter++ instead of counter = counter + 1. This is a shorthand way to increase the value of a variable by 1 in Java.Also, if you want to print the numbers on the same line, you can simply add a space (
" ") after the variable using the + sign. Here's how it looks:
import java.util.*;
public class Main{
public static void main(String[]args){
for (int counter=0;counter<11;counter++){
System.out.print(counter+" ");
}
}
}
import java.util.*;
public class Main{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
Integer n= sc.nextInt();
int sum=0;
for (int i=1; i<=n;i++){
sum = sum+i;
}
System.out.println(sum);
}
}
📝 Homework Question:
for loop and take input from the user, try this:n as input from the user and prints the multiplication table of that number.While Loop:
A while loop in Java is used when you want to repeat a block of code as long as a certain condition is true. It checks the condition before running the code block.
One common use of the while loop is when the number of repetitions isn’t known in advance. For example, it can be used to keep asking the user for input until they enter a specific value — or even to run infinitely if needed.
Infinite While Loops:
while loop for infinite execution by setting the condition to always be true. This is often used in programs that should keep running until the user decides to exit.import java.util.*;
public class Main {
public static void main(String[] args) {
while (true) {
System.out.println(1);
}
}
}
Syntax of While loop in java:
import java.util.*;
public class Main {
public static void main(String[] args) {
int n=0;
while(n<11){
System.out.println(n);
n++;
}
}
}
📝 Homework Question 1:
while loops.n natural numbers using a while loop.📝 Homework Question 2:
while loop and take input from the user, try this:n as input from the user and prints the multiplication table of that number using a while loop.Do While Loops:
Sometimes, you want a block of code to run at least once, no matter what. That’s exactly where the do-while loop comes in handy.
Unlike the while loop, which checks the condition before executing the code, the do-while loop checks the condition after the code has already run once. This guarantees that the code inside the loop runs at least one time — even if the condition turns out to be false right away.
Syntax:
do-while loop when you must run the code block at least once — for example, showing a menu to the user or asking for input until it meets a condition.public class Main {
public static void main(String[] args) {
int n=0;
do{
System.out.println(n);
n++;
}while (n<11);
import java.util.*;
public class Main {
public static void main(String[] args) {
int n=12;
do{
System.out.println("adda4coding");
}while (n<11);
}
}
do-while loop, the program first executes the do block and then checks the condition. For example, if we initialize n = 12, the loop will print "adda4coding" once. After that, it checks the condition n < 11, which is false, so the loop terminates immediately.📝 Homework Question 1:
while loops.n natural numbers using a do-while loop.📝 Homework Question 2:
while loop and take input from the user, try this:n as input from the user and prints the multiplication table of that number using a do-while loop.Question 1: Suppose you are Raghav, and your teacher asks you to take the name and marks of a student as input, and determine whether the student has passed or failed.
Programme: import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String name= sc.next();
int mrks=sc.nextInt();
if(mrks<33){
System.out.println("fail");
}
else{
System.out.println("pass");
}
}
}
Question: Suppose pinky had made a switch board of 8 switches. you have to use the switch function to take the output. the work of each switch can be determine by the coder
programme:import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int button=sc.nextInt();
switch(button){
case 1:
System.out.println("You are best friend");
break;
case 2:
System.out.println("Namaste");
break;
case 3:
System.out.println("hello bhaiyo");
break;
case 4:
System.out.println("Agent 007 Reporting");
break;
case 5:
System.out.println("aada4coding");
break;
case 6:
System.out.println("java switches is going on");
break;
case 7:
System.out.println("Ola");
case 8: int a=sc.nextInt();
int b=sc.nextInt();
System.out.println(a+b);
break;
default:
System.out.println("wrong choice entered");
}
}
}
Question: Write the code to print the pattern:111112222333445programme:# Number of rows
n = 5
for i in range(1, n + 1):
# Print the number without leading spaces
print(str(i) * (n - i + 1))Question: Write the code to print the pattern:123456789101112131415programme:num = 1 # Starting number
for i in range(1, 6): # 5 rows
for j in range(i): # i numbers in each row
print(num, end="")
num += 1
print()Question: Write the code to print the pattern:101101010110101Programme:for i in range(1, 6): # Loop for 5 rows
for j in range(1, i + 1): # Loop for columns in each row
if (i + j) % 2 == 0:
print(1, end="")
else:
print(0, end="")
print()Question: Write the code to print the pattern:1____112___21 [Take _ as a space not the symbol or character]123__3211234_4321123454321Programme:n = 5 # Number of rows
for i in range(1, n + 1):
# Print increasing numbers from 1 to i
for j in range(1, i + 1):
print(j, end="")
# Print spaces (2*(n-i)) times
for k in range(2 * (n - i)):
print(" ", end="")
# Print decreasing numbers from i to 1
for j in range(i, 0, -1):
print(j, end="")
print()Question: As in previous blog i gave you the code for Geometric progression,now you have to create the code for arithmetic and harmonic progression.Programme: Arithmetic Progression# Arithmetic Progression generator
a = int(input("Enter the first term of AP: "))
d = int(input("Enter the common difference: "))
n = int(input("Enter the number of terms: "))
print("Arithmetic Progression:")
for i in range(n):
term = a + i * d
print(term, end=" ")Programme: Harmonic Progression:# Harmonic Progression (HP)
# HP is the reciprocal of an Arithmetic Progression
a_hp = int(input("Enter the first term of AP for HP: "))
d_hp = int(input("Enter the common difference: "))
n_hp = int(input("Enter the number of terms: "))
print("Harmonic Progression:")
for i in range(n_hp):
hp_term = 1 / (a_hp + i * d_hp)
print(hp_term, end=" ")Question: Write the code to print starting 100 prime numbers.programme:count = 0 # Initialize a counter to keep track of how many prime numbers we've found
num = 2 # Start checking for primes from the number 2
while count < 100: # Loop until we find 100 prime numbers
is_prime = True # Assume the current number is prime
# Check if the number is divisible by any number from 2 to num // 2
for i in range(2, (num // 2) + 1):
if num % i == 0: # If it is divisible, it's not a prime number
is_prime = False
break # No need to check further, break the loop
if is_prime: # If the number is still considered prime
print(num) # Print the prime number
count += 1 # Increase the count of prime numbers found
num += 1 # Move to the next number to checkQuestion: Write the code to take the input of number from the user and thenyou have to check weather the number is prime or not.Programme:num = int(input("Enter a number: "))
if num <= 1:
print("Not a prime number")
else:
for i in range(2, (num // 2) + 1):
if num % i == 0:
print("Not a prime number")
break
else:
print("Prime number")Question: This question is may be tough for the beginners but easy to writethe choice based programme in which you will enter your choice and programmeworks accordingly.Output should be: Enter the choice:1x=10 numbers should entered by the usery=20s=x+ys=30Programme:ch="y" # Initial value to enter the loop
a=int(input("enter the number")) # Taking first number input
b=int(input("enter the number")) # Taking second number input
while ch=="y"or ch=="Y": # Loop runs as long as user inputs 'y' or 'Y'
print("Here are your choices" + "\n", "1.Sum" + "\n", "2.Difference" + "\n", "3. sum_of_square" + "\n",
"4.divisibility_check_of_Difference" + "\n", "5.Exit") # Displaying menu options
choice = int(input("enter the choice")) # Taking user choice
if choice ==1: # If choice is 1, perform sum
sum=a+b # Calculate sum
print(sum) # Print result
elif choice ==2: # If choice is 2, perform difference
diff=a-b # Calculate difference
print(diff) # Print result
elif choice==3: # If choice is 3, perform sum of squares
sum_of_square= (a**2)+(b**2) # Calculate sum of squares
print(sum_of_square) # Print result
elif choice==4: # If choice is 4, check divisibility of difference
divisibility_check_of_Difference=a-b # Calculate difference
if divisibility_check_of_Difference % 2==0: # Check if divisible by 2
print("divisible by 2") # Print if divisible
elif choice==5: # If choice is 5, exit the loop
break # Exit loop
else: # If invalid choice
print("Wrong choice entered") # Inform user about wrong input
ch=input("do you want to continue??(Y/N)") # Ask user to continue or notConclusion:
Loops are one of the most important building blocks in programming — and in
this blog, you’ve learned how they work in Java with practical examples.
Whether it’s theforloop for a known number of repetitions, thewhileloop
for more flexible conditions, or thedo-whileloop that ensures the code runs
at least once — each loop has its unique use-case in real-world programming.
You also explored how to handle user input, use conditions, apply logic with
switch cases, and create number-based patterns, progressions, and even prime
number programs. These hands-on examples will help strengthen your Javafundamentals and give you the confidence to build more complex programs.Keep practicing these patterns and problems, and soon you'll find yourselfthinking like a real programmer!if you guys are loving this blog then you must also visit my previous blog inI had talked about all the basics of java: Basics of Java for Beginners.🎯 Tip: Start creating your own variations of these problems to challenge
yourself — that’s the fastest way to learn and grow!




3 Comments
Great coding for lerning good job beta
ReplyDeleteGreat
ReplyDeleteGreat work
ReplyDelete