Loop Structure in Java जावा में लूप स्ट्रक्चर for loop, while loop, do...while loop
Java supports three types of loops: for loop, while loop, and do...while loop. These loops are used when a task needs to be repeated multiple times.
जावा तीन मुख्य प्रकार के लूप का समर्थन करता है: for loop, while loop, और do...while loop. इनका उपयोग तब किया जाता है जब हमें एक ही कोड को बार-बार चलाना हो।
✅ (a) for
Loop – Entry-Controlled Loop
A for
loop checks the condition before entering the loop. It has initialization, condition, and update parts written in a single line, separated by semicolons. It's ideal when the number of iterations is known.
for
लूप एक एंट्री कंट्रोल लूप होता है जिसमें कंडीशन को पहले चेक किया जाता है। इसमें इनिशियलाइजेशन, कंडीशन और अपडेशन एक ही लाइन में लिखे जाते हैं और अर्धविराम से अलग किए जाते हैं। इसका उपयोग तब किया जाता है जब पहले से पता हो कि लूप कितनी बार चलेगा।
Java Program:
public class ForLoopExample {
public static void main(String[] args) {System.out.println("For Loop Output:");for (int i = 1; i <= 5; i++) {System.out.println("Value of i: " + i);}}}
📤 Output:
Value of i: 1
Value of i: 2Value of i: 3Value of i: 4Value of i: 5
✅ (b) while
Loop – Entry-Controlled Loop
The while
loop only contains the condition. Initialization is done before the loop, and updating happens inside the loop. It’s useful when the number of iterations is not known beforehand.
while
लूप में केवल कंडीशन दी जाती है। इनिशियलाइजेशन लूप से पहले किया जाता है और अपडेशन लूप के भीतर होता है। यह तब उपयोगी होता है जब यह पहले से न पता हो कि लूप कितनी बार चलेगा।
Java Program:
public class WhileLoopExample {
public static void main(String[] args) {int i = 1;System.out.println("While Loop Output:");while (i <= 5) {System.out.println("Value of i: " + i);i++;}}}
📤 Output:
Value of i: 1
Value of i: 2Value of i: 3Value of i: 4Value of i: 5
✅ (c) do...while
Loop – Exit-Controlled Loop
In do...while
, the loop runs at least once regardless of the condition because the condition is checked at the end. It's best when the loop must execute at least once.
do...while
लूप में लूप का ब्लॉक कम से कम एक बार जरूर चलता है क्योंकि कंडीशन अंत में चेक की जाती है। इसका उपयोग तब होता है जब आप चाहते हैं कि लूप एक बार जरूर चले।
Java Program:
public class DoWhileExample {
public static void main(String[] args) {int i = 1;System.out.println("Do-While Loop Output:");do {System.out.println("Value of i: " + i);i++;} while (i <= 5);}}
📤 Output:
Value of i: 1
Value of i: 2Value of i: 3Value of i: 4Value of i: 5
📌 Conclusion
-
for
loop is best when the number of iterations is known. -
while
loop is ideal when the number of iterations is unknown. -
do...while
loop guarantees at least one execution of the loop body. -
for
लूप तब उपयोगी होता है जब iterations पहले से ज्ञात हों। -
while
लूप तब उपयोगी होता है जब iterations का count पहले से न पता हो। -
do...while
लूप का उपयोग तब करें जब आप चाहते हों कि लूप कम से कम एक बार चले।
Comments
Post a Comment