Looping
Program में Statements (स्टेटमेट्स) के किसी ब्लॉक को बार-बार Execute(एग्जीक्यूट) करने की प्रक्रिया को Looping(लूपिंग) कहते हैं। एक Statement Block(स्टेटमेट ब्लॉक) को Loop(लूप) की सहायता से कई बार Execute(एग्जीक्यूट) कराया जा सकता है। Looping(लूपिंग) में Statements (स्टेटमेट्स) का Block(ब्लॉक) तब तक Execute(एग्जीक्यूट) होता है जब तक लूप में दी गई Condition(कण्डीशन) true रहती है।
C++ में लूप के मुख्यतः दो भाग होते हैं
- loop की body या block
- Control Statement(कंट्रोल स्टेटमेंट )
- entry controlled loop
- exit controlled loop
C++ में Looping(लूपिंग) के लिए तीन Control Statement(कंट्रोल स्टेटमेंट) होते हैं
whileLoopdo...whileLoopforLoop
C Statements
while लूप entry controlled loop की श्रेणी में आता है क्योंकि इसमें लूप में प्रवेश करने से पहले Condition check होती है। while स्टेटमेंट का प्रारूप निम्न प्रकार होता है -
while (condition) {
// body of the loop
}Explain Syntax:-
-
whileloop(लूप) में सबसे पहलेconditioncheck की जाती हैं। - यदि
conditiontrueहोती है , तो लूप के अंदर का code Execute किया जाता है। - इस के बाद
conditionफिर से check की जाती है, यदिconditiontrueहोती है , तो लूप के अंदर का code Execute किया जाता है। - यह प्रक्रिया है तब तक जारी रहती है जब तक की
conditionfalseना हो जाये। - जब का
conditionfalseहो जाती हैं तो लूप समाप्त हो जाता है।
Example #01:-
Output:-
1 2 3 4 5
Explain Example:-
उपरोक्त program(प्रोग्राम) का प्रवाह जब while ( x <=5) पर पहुंचेगा तो x का मान 1 होगा। चूंकि (1<=5) कंडीशन true होती हैं, अतः प्रोग्राम का प्रवाह while ब्लॉक में हो जाएगा और i की value प्रिंट हो जाएगी । तत्पश्चात् ++ वेरिएबल x के मान में increment कर उसका मान 2 कर देगा। जब प्रवाह while ब्लॉक के अंत में आएगा तो प्रवाह को वापस while स्टेटमेंट पर भेज दिया जाएगा। अब चूंकि ( x <=5) अर्थात 2<=5 का परिणाम वापस true है, अत: प्रवाह वापस while ब्लॉक में प्रवेश कर जाएगा। यह प्रक्रिया तब तक चलती रहेगी जब तक कि x का मान 5 से अधिक नहीं हो जाता है।
यहां बताया गया है कि Program कैसे काम करता है।
| Iteration | Variable | i <= 5 | Action |
|---|---|---|---|
| 1st | i = 1 | true | 1 is printed and i is increased to 2. |
| 2nd | i = 2 | true | 2 is printed and i is increased to 3. |
| 3rd | i = 3 | true | 3 is printed and i is increased to 4 |
| 4th | i = 4 | true | 4 is printed and i is increased to 5. |
| 5th | i = 5 | true | 5 is printed and i is increased to 6. |
| 6th | i = 6 | false | The loop is terminated |
Example #02:
Sum of Positive Numbers Only
Output:-
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
0 Comments