B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Java For Loop | Login Technologies

Java Loop

What is a Loop?
A loop in programming allows you to execute a block of code repeatedly until a certain condition is met.

लूप क्या है?
प्रोग्रामिंग में लूप आपको एक कोड ब्लॉक को तब तक दोहराने की अनुमति देता है जब तक कोई खास शर्त पूरी न हो जाए।

Why use Loops?
Loops help avoid repetitive code, make your programs shorter, efficient, and easy to maintain.

लूप क्यों इस्तेमाल करें?
लूप से आप बार-बार एक जैसा कोड लिखने से बचते हैं, जिससे प्रोग्राम छोटा, कुशल और आसान बनता है।

Advantages of Loops:

  • Reduces code repetition
  • Makes code easy to read and maintain
  • Allows dynamic execution based on conditions
  • Useful for processing collections or repeated tasks

लूप के फायदे:

  • कोड की पुनरावृत्ति कम करता है
  • कोड को पढ़ने और समझने में आसान बनाता है
  • शर्तों के आधार पर कोड को बार-बार चलाता है
  • कलेक्शन या बार-बार होने वाले कार्यों के लिए उपयोगी

Syntax of for Loop in Java:

for (initialization; condition; update) {
    // code to be executed repeatedly
}

Example 1: Print Numbers 1 to 5

public class PrintNumbers {
    public static void main(String[] args) {
        for(int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

Prints numbers from 1 to 5.

1 से 5 तक की संख्याएँ प्रिंट करता है।

Output:
1 2 3 4 5


Example 2: Sum of First 10 Natural Numbers

public class SumNumbers {
    public static void main(String[] args) {
        int sum = 0;
        for(int i = 1; i <= 10; i++) {
            sum += i;
        }
        System.out.println("Sum = " + sum);
    }
}

Calculates sum of first 10 natural numbers.

पहली 10 प्राकृतिक संख्याओं का योग निकालता है।

Output:
Sum = 55


Example 3: Print Even Numbers 2 to 10

public class EvenNumbers {
    public static void main(String[] args) {
        for(int i = 2; i <= 10; i += 2) {
            System.out.print(i + " ");
        }
    }
}

Prints even numbers from 2 to 10.

2 से 10 तक की सम संख्याएँ प्रिंट करता है।

Output:
2 4 6 8 10


Example 4: Factorial of 5

public class Factorial {
    public static void main(String[] args) {
        int fact = 1;
        for(int i = 1; i <= 5; i++) {
            fact *= i;
        }
        System.out.println("Factorial = " + fact);
    }
}

Calculates factorial of 5.

5 का फैक्टोरियल निकालता है।

Output:
Factorial = 120


Example 5: Countdown from 5 to 1

public class Countdown {
    public static void main(String[] args) {
        for(int i = 5; i > 0; i--) {
            System.out.println(i);
        }
        System.out.println("Go!");
    }
}

Counts down from 5 to 1 and then prints Go!

5 से 1 तक उल्टी गिनती करता है, फिर Go! प्रिंट करता है।

Output:
5 4 3 2 1 Go!