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:
लूप के फायदे:
for (initialization; condition; update) {
// code to be executed repeatedly
}
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
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
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
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
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!