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
Last post Chapter में हमने while लूप को समझ लिया था अब हम do-while को समझेंगे।
2. do-while Loop:-
do-while लूप exit controlled loop की श्रेणी में आता है क्योंकि इसमें loop(लूप) से बाहर निकलते समय Condition(कण्डीशन) check(जाँच) होती है। while लूप की भांति यह लूप भी तब तक execute(एग्जीक्यूट) होता है जब तक कण्डीशन true होती है। यह लूप कम से कम एक बार अवश्य रन होता है, वहीं while लूप हो सकता है कि किसी कंडीशन में एक बार भी रन ना हो।
do स्टेटमेंट का निम्न प्रारूप होता है.
initialization section;
do
{
Statement 1;
Statement 2;
. . . . . . . . .
. . . . . . . . .
Statement n;
}while(Test Condition);
यदि Loop कीconditionहमेशाtrueहोती है तो लूप अनंत समय तक चलता है (जब तक कि मेमोरी भर न जाए)।
उदाहरण के लिए,
// infinite while loop
while(true) {
// body of the loop
}do...while infinite लूप का एक उदाहरण यहां दिया गया है ।
// infinite do...while loop
int count = 1;
do {
// body of loop
}
while(count == 1);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 4:
Positive Numbers का Sum(योग) ज्ञात करना
Output:-
Enter a number: 6
Enter a number: 7
Enter a number: 12
Enter a number: 0
Enter a number: -2
The sum is 25
0 Comments