DMCA.com Protection Status Java Programming Lesson 5 | Loops powerful features in Java - ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer

Header Ads

Java Programming Lesson 5 | Loops powerful features in Java

LESSON-5: LOOP 

🔥 Let's jump into Lesson-5: Loops — one of the most powerful features in Java.



Loops are one of the most powerful building blocks of any programming language. They allow your program to repeat tasks automatically, without writing the same code multiple times. Once you master loops, you unlock the ability to build dynamic programs, automate repetitive logic, and handle large amounts of data with ease.

This lesson will guide you through the fundamentals of loops in Java, including:

  • Why loops are important
  • Different types of loops
  • Syntax and real examples
  • When to use which loop
  • Common mistakes beginners should avoid

Let’s get started!

🔷 What Are Loops in Java?

A loop is a control structure that repeats a block of code as long as a condition is true.

Java provides four main types of loops:

  1. for loop
  2. while loop
  3. do…while loop
  4. Enhanced for-each loop

🔷 Why Are Loops Important?

Loops help programmers:

  • Avoid writing duplicate code
  • Process lists, arrays, and collections
  • Handle large repetitive tasks
  • Save time and improve code readability
  • Build programs like calculators, games, data readers, automation tools, etc.

Without loops, you would write the same line again and again:

❌ Without Loop

System.out.println(1); System.out.println(2); System.out.println(3);

✔ With Loop

for (int i = 1; i <= 3; i++) { System.out.println(i); }

📘 Lesson 5 — Loops (for, while, do-while)

Loops help us repeat code multiple times without rewriting it.


✅ 1️⃣ for Loop

We know how many times repetition is needed.

Structure:

for(initialization; condition; increment/decrement){ // code }

Example:

for(int i = 1; i <= 5; i++){ System.out.println("Number: " + i); }

✅ Output:

Number: 1 Number: 2 Number: 3 Number: 4 Number: 5

✅ 2️⃣ while Loop

We don't always know the number of repetition beforehand — loop continues while condition is true.

Structure:

while(condition){ // code }

Example:

int i = 1; while(i <= 5){ System.out.println(i); i++; }

✅ 3️⃣ do-while Loop

Executes at least once, even if condition is false.

Structure:

do{ // code } while(condition);

Example:

int i = 1; do{ System.out.println(i); i++; }while(i <= 5);

✅ Extra: break & continue

KeywordPurpose
break             Stops loop immediately
continue             Skips current iteration

Example:

for(int i=1; i<=5; i++){ if(i == 3){ continue; // Skip 3 } System.out.println(i); }

Output:

1 2 4 5

🔷 Enhanced for-each Loop — Best for Arrays & Collections


Syntax:

for (type variable : array) {

// use variable
}

Example:

int[] marks = {85, 90, 75, 88}; for (int m : marks) {
System.out.println(m);
}

Best Use:

  • Arrays
  • Lists

Reading values without using index

🔷 Infinite Loops (Avoid These!)

❌ Example of infinite loop:

while (true) { System.out.println("Runs forever!"); }

Make sure your loop has a valid exit condition.


🔷 Real-World Examples of Loops


✔ Example 1: Sum of 1–10

int sum = 0;

for (int i = 1; i <= 10; i++) { sum += i; } System.out.println(sum);


✔ Example 2: Multiplication Table

int n = 5;

for (int i = 1; i <= 10; i++) { System.out.println(n + " x " + i + " = " + (n * i)); }


✔ Example 3: Repeat until user types “exit”

Scanner input = new Scanner(System.in);

String value; do { System.out.print("Enter text (type exit to stop): "); value = input.nextLine(); } while (!value.equals("exit"));

🔷 Common Mistakes Beginners Make

❌ Forgetting to update the loop variable

Causes infinite loops

❌ Using = instead of ==

= assigns,
== compares

❌ Wrong loop condition

Loop never runs
Loop runs forever

❌ Array index errors

marks[5] // invalid if array size = 5

✅ Full Practical Example

public class LoopExample { public static void main(String[] args) { // For Loop System.out.println("For Loop:"); for(int i = 1; i <= 5; i++){ System.out.println(i); } // While Loop System.out.println("\nWhile Loop:"); int j = 1; while(j <= 5){ System.out.println(j); j++; } // Do-While Loop System.out.println("\nDo-While Loop:"); int k = 1; do{ System.out.println(k); k++; }while(k <= 5); } }

🔷 Summary of What You Learned

In this lesson, you learned:

  • What loops are
  • Types of loops in Java
  • for, while, do…while, and for-each loops
  • Using break and continue
  • Avoiding infinite loops
  • Real-world examples and best practices

Loops are essential for building efficient, professional Java programs. You’ll use them in data processing, games, automation, calculations, user input handling, and more.


📝 Exercise for You ✅

Write programs using:

1️⃣ for loop → print numbers 1 to 10
2️⃣ while loop → print even numbers 2 to 20
3️⃣ do-while loop → print numbers decreasing from 5 to 1

Reply with your:

✅ Code
✅ Output

I will check and give feedback ✅🔥


🎯 Quick Quiz

1️⃣ Which loop must run at least once?
A) for
B) while
C) do-while

2️⃣ Which keyword exits loop immediately?
A) break
B) stop
C) quit

Reply format:
1 → ?, 2 → ?


✅ Lesson-5 Completed!

Ready for next lessons?

Lesson-6: Arrays (1D & 2D)
or
Lesson-6: Strings (String class & methods)

Which one should we learn first? 😃


▶ NEXT PART - Lesson 6 Part-1 | Arrays in Java Explained


Frequently Asked Questions (FAQs)

What are loops used for in Java?

Loops in Java are used to execute a block of code repeatedly until a specific condition is met. They help reduce repetitive code and automate iterative tasks.

What are the main types of loops in Java?

Java provides four main loop types: for, while, do-while, and the enhanced for-each loop for iterating over collections and arrays.

How does a for loop work in Java?

A for loop runs a block of code repeatedly by using an initialization expression, condition check, and update step. It’s used when the number of iterations is known.

What is the difference between while and do-while loops?

The while loop checks the condition before running the loop body, while the do-while loop executes the loop body at least once before checking the condition.

What is the enhanced for-each loop?

The enhanced for-each loop provides a simplified way to iterate over arrays or collections without using index variables. It improves readability and reduces errors.

When should I use break and continue?

The break statement stops a loop immediately, while continue skips the current iteration and moves to the next one.

Can loops be nested in Java?

Yes. Java allows nested loops, where one loop runs inside another. Nested loops are useful for working with multidimensional arrays or complex repetitive logic.

What are infinite loops and how can they be avoided?

An infinite loop occurs when the loop condition never becomes false. To avoid this, ensure that the loop's update step modifies variables correctly and leads toward the stopping condition.

No comments

Thank You For Visit My Website.
I Will Contact As Soon As Possible.

Theme images by 5ugarless. Powered by Blogger.