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(कंट्रोल स्टेटमेंट) होते हैं
while
Loopdo...while
Loopfor
Loop
Last Chapter में हमने while व do-while लूप को समझ लिया था अब हम for को समझेंगे।
3.) For Loop:-
यह भी एक Entry controlled लूप होता है। इसका प्रयोग सामान्यतः तब किया जाता है जब लूप को निश्चित बार रन करना हो। इसका प्रारूप निम्नानुसार होता है:-
for (initialization; condition; update) {
// body of-loop
}
Explain
initialization
- Variable(वेरिएबल्स) को Initialize(इनिशियलाइज़ ) करता है और केवल एक बार Execute किया जाता हैcondition
- अगर conditiontrue
हो तोfor
लूप की body Execute किया जाता है,
andfalse
होने पर for लूप terminated(समाप्त) हो जाता है।update
- आरंभिक Variable की value को update करता है और फिर से Condition check की जाती है
Example #01:-
Output:-
1 2 3 4 5
यहां बताया गया है कि यह Program कैसे काम करता है
Iteration | Variable | i <= 5 | Action |
---|---|---|---|
i = 1 | not checked | 1 is printed and i is increased to 2 | |
1st | i = 2 | true | 2 is printed and i is increased to 3 |
2nd | i = 3 | true |
3 is printed and i is increased to 4 |
3rd | i = 4 | true | 4 is printed and i is increased to 5 |
4th | i = 5 | true | 5 is printed and i is increased to 6 |
5th | i = 6 | false | The loop is terminated |
Example #02:-
Output:-
Enter a positive integer: 10
Sum = 55
Example #03:-
निम्न उदाहरणinitialization
तथा increment/decrement का प्रयोग for में किए बिना 1
से 5
तक संख्याएं प्रिंट की गई है।
Output:-
a = 1
a = 2
a = 3
a = 4
a = 5
Explain Example:-
उपरोक्त उदाहरण भी वेरिएबल को प्रारंभिक वैल्यू तथा उसमें इंक्रीमेंट अथवा डिक्रीमेट स्टेटमेंट में नहीं दी गई है। यह दोनों ही कार्य क्रमशः forfor
के पहले तथा for स्टेटमेंट के ब्लॉक में किए गए है।
Example #04:-
निम्न उदाहरण में एक से अधिक variable(वेरिएबल्स) को initializeinitialize
तथा increase/decrease करते हुए 1 से 5 एवं 5 से 1 तक संख्याएं साथ-साथ प्रिंट की गई है।
Output:-
a = 1 b = 5
a = 2 b = 4
a = 3 b = 3
a = 4 b = 2
a = 5 b = 1
Explain Example:-
(,)
का प्रयोग किया जाता है।
0 Comments