SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
FLOW OF CONTROL

The flow of control jumps from one part of the
program to another,depending on calculations
performed in the program.

Program statements that cause such jumps are
 called control statements. There are two major
categories: loops and decisions.
FLOW OF CONTROL

                          STATEMENTS




Compound                                                Simple



 Selection/Decision                  Iteration/Loop



FL else    Switch care     For            While       Do-While
               Jump statements



Break       Continue         Go to          Return       Exit
 Statements are the instructions given to the computer to perform
  any kind of action , be it data movements, be it making decisions or
  be it repeating actions.
 Statements are the smallest executing unit of a C++ program.
   COMPOUND STATEMENT (BLOCK )
  A compound statement in C++ is a sequence of statements enclosed by
    a pair of branches { }.

                      {
                              statements 1 ;
                              statements 2 ;
                                  :
                          }
                                represents a compound statement
Sequence = The sequence construct means the statements are
  being executed sequentially. This represents the default flow of
  statement.
                          STATEMENT 1



                         STATEMENT 2



                         STATEMENT 3
                                          The sequence construct
Selection = The selection construct means the execution of
   statements depending upon a condition evaluates true, a set of
   statements is followed.


                                    A set of statements
                          true
             Condition             Statement 1     Statement 2
                ?




            Statement 1
Another
set of
statement   Statement 2




                     The selection construction
if-else Statement Syntax

• Formal syntax:
  if (<boolean_expression>)
       <yes_statement>
  else
       <no_statement>
• Note each alternative is only
  ONE statement!
• To have multiple statements execute in
  either branch  use compound statement
Compound Statement in
            Action
• Note indenting in this example:
  if (myScore > yourScore)
  {
      cout << "I win!n";
      wager = wager + 100;
  }
  else
  {
      cout << "I wish these were golf scores.n";
      wager = 0;
  }
Nested Statements

• if-else statements contain smaller
  statements
  – Compound or simple statements (we’ve seen)
  – Can also contain any statement at all, including
    another if-else stmt!
  – Example:
    if (speed > 55)
        if (speed > 80)
            cout << "You’re really speeding!";
        else
            cout << "You’re speeding.";
     • Note proper indenting!
The switch Statement
 A new statement for controlling multiple branches
 Uses controlling expression which returns bool data type (true or false)
The switch: multiple case
                      labels

Execution "falls through" until break
   switch provides a "point of entry"
   Example:
   case "A":
   case "a":
      cout << "Excellent: you got an "A"!n";
      break;
   case "B":
   case "b":
      cout << "Good: you got a "B"!n";
      break;
   Note multiple labels provide same "entry"
Switch Pitfalls/Tip




Forgetting the break;
   No compiler error
   Execution simply "falls through" other cases until break;
Biggest use: MENUs
   Provides clearer "big-picture" view
   Shows menu structure effectively
   Each branch is one menu choice
LOOP


Loops cause a section of your program to be repeated
a certain number of times. The repetition continues while
 a condition is true. When the condition becomes false,
the loop ends and control passes to the statements
following the loop.
Iteration = The iteration construct means repetition of a set
  of statements depending upon a condition - test. Till the
  time a condition true { or false depending upon the loop },
  a set-of-statements are repeated again and again. As soon
  as the condition becomes false { or true },

                                                 False
                      Condition
                         ?
                                                    The exit condition

                                 True


                      Statement 1


                                               The loop body
                       Statement 2



                   The interaction construct
3 Types of loops in C++
       for
           Natural "counting" loop
      do-while
           Least flexible
           Always executes loop body
           at least on
      while
           Most flexible
           No “restrictions”
For Loop Syntax


for (Init_Action; Bool_Exp; Update_Action)
       Body_Statement

Like if-else, Body_Statement can be
a block statement
For Loop Example

for (count=0;count<3;count++)
{
       cout << "Hi "; // Loop Body
}

How many times does loop body execute?
Initialization, loop condition and update all
"built into" the for-loop structure!
A natural "counting" loop
While Loop Syntax
While Loop Example

 Consider:
count = 0;              // Initialization
while (count < 3)       // Loop Condition
{
       cout << "Hi ";   // Loop Body
       count++;         // Update expression
}
   Loop body executes how many times?
Do while Loop Syntax
Do while Loop Example
count = 0;         // Initialization
do
{
      cout << "Hi ";      // Loop Body
      count++;            // Update expression
} while (count < 3);      // Loop Condition
   Loop body executes how many times?
   do-while loops always execute body at
   least once!
Loop Issues
Loop’s condition expression can be ANY
boolean expression.
Examples:
      while (count<3 && done!=0)
  {
      // Do something
  }
      for (index=0;index<10 && entry!=-99)
  {
      // Do something
  }
Loop Pitfalls: Misplaced ;

Watch the misplaced ; (semicolon)
  Example:
  while (response != 0) ;
  {
     cout << "Enter val: ";
     cin >> response;
  }
  Notice the ";" after the while condition!
Result here: INFINITE LOOP!
Loop Pitfalls: Infinite Loops


Loop condition must evaluate to false at
some iteration through loop
   If not  infinite loop.
   Example:
   while (1)
   {
       cout << "Hello ";
   }
   A perfectly legal C++ loop  always infinite!
The break and continue Statement

Flow of Control
  Recall how loops provide "graceful" and
  clear flow of control in and out
  In RARE instances, can alter natural flow
break;
  Forces loop to exit immediately.
continue;
   Skips rest of loop body
These statements violate natural flow
  Only used when absolutely necessary!
Nested Loops

Recall: ANY valid C++ statements can be
inside body of loop
This includes additional loop statements!
   Called "nested loops"
Requires careful indenting:
for (outer=0; outer<5; outer++)
   for (inner=7; inner>2; inner--)
      cout << outer << inner;
   Notice no { } since each body is one statement
   Good style dictates we use { } anyway
Control statements

Weitere ähnliche Inhalte

Was ist angesagt?

Conditionalstatement
ConditionalstatementConditionalstatement
ConditionalstatementRaginiJain21
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ LanguageWay2itech
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationBadrul Alam
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C LanguageShaina Arora
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++Nitin Jawla
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 

Was ist angesagt? (20)

Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition Presentation
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
Loops c++
Loops c++Loops c++
Loops c++
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
C functions
C functionsC functions
C functions
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
Nested loops
Nested loopsNested loops
Nested loops
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 

Andere mochten auch

Andere mochten auch (6)

C# conditional branching statement
C# conditional branching statementC# conditional branching statement
C# conditional branching statement
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statements
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Pricing Ppt
Pricing PptPricing Ppt
Pricing Ppt
 

Ähnlich wie Control statements

Ähnlich wie Control statements (20)

C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structures
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdf
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
Control statements
Control statementsControl statements
Control statements
 
C language 2
C language 2C language 2
C language 2
 
Control structures
Control structuresControl structures
Control structures
 
Control statement
Control statementControl statement
Control statement
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Flow of control
Flow of controlFlow of control
Flow of control
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
 
While loop
While loopWhile loop
While loop
 
cpu.pdf
cpu.pdfcpu.pdf
cpu.pdf
 
whileloop-161225171903.pdf
whileloop-161225171903.pdfwhileloop-161225171903.pdf
whileloop-161225171903.pdf
 
Flow Control (C#)
Flow Control (C#)Flow Control (C#)
Flow Control (C#)
 
Loops and iteration.docx
Loops and iteration.docxLoops and iteration.docx
Loops and iteration.docx
 
Flow of control c++
Flow of control c++Flow of control c++
Flow of control c++
 
07 flow control
07   flow control07   flow control
07 flow control
 
Chapter 9 - Loops in C++
Chapter 9 - Loops in C++Chapter 9 - Loops in C++
Chapter 9 - Loops in C++
 

Kürzlich hochgeladen

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Kürzlich hochgeladen (20)

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Control statements

  • 1.
  • 2. FLOW OF CONTROL The flow of control jumps from one part of the program to another,depending on calculations performed in the program. Program statements that cause such jumps are called control statements. There are two major categories: loops and decisions.
  • 3. FLOW OF CONTROL STATEMENTS Compound Simple Selection/Decision Iteration/Loop FL else Switch care For While Do-While Jump statements Break Continue Go to Return Exit
  • 4.  Statements are the instructions given to the computer to perform any kind of action , be it data movements, be it making decisions or be it repeating actions.  Statements are the smallest executing unit of a C++ program. COMPOUND STATEMENT (BLOCK ) A compound statement in C++ is a sequence of statements enclosed by a pair of branches { }. { statements 1 ; statements 2 ; : } represents a compound statement
  • 5. Sequence = The sequence construct means the statements are being executed sequentially. This represents the default flow of statement. STATEMENT 1 STATEMENT 2 STATEMENT 3 The sequence construct
  • 6. Selection = The selection construct means the execution of statements depending upon a condition evaluates true, a set of statements is followed. A set of statements true Condition Statement 1 Statement 2 ? Statement 1 Another set of statement Statement 2 The selection construction
  • 7. if-else Statement Syntax • Formal syntax: if (<boolean_expression>) <yes_statement> else <no_statement> • Note each alternative is only ONE statement! • To have multiple statements execute in either branch  use compound statement
  • 8. Compound Statement in Action • Note indenting in this example: if (myScore > yourScore) { cout << "I win!n"; wager = wager + 100; } else { cout << "I wish these were golf scores.n"; wager = 0; }
  • 9. Nested Statements • if-else statements contain smaller statements – Compound or simple statements (we’ve seen) – Can also contain any statement at all, including another if-else stmt! – Example: if (speed > 55) if (speed > 80) cout << "You’re really speeding!"; else cout << "You’re speeding."; • Note proper indenting!
  • 10. The switch Statement  A new statement for controlling multiple branches  Uses controlling expression which returns bool data type (true or false)
  • 11.
  • 12. The switch: multiple case labels Execution "falls through" until break switch provides a "point of entry" Example: case "A": case "a": cout << "Excellent: you got an "A"!n"; break; case "B": case "b": cout << "Good: you got a "B"!n"; break; Note multiple labels provide same "entry"
  • 13. Switch Pitfalls/Tip Forgetting the break; No compiler error Execution simply "falls through" other cases until break; Biggest use: MENUs Provides clearer "big-picture" view Shows menu structure effectively Each branch is one menu choice
  • 14. LOOP Loops cause a section of your program to be repeated a certain number of times. The repetition continues while a condition is true. When the condition becomes false, the loop ends and control passes to the statements following the loop.
  • 15. Iteration = The iteration construct means repetition of a set of statements depending upon a condition - test. Till the time a condition true { or false depending upon the loop }, a set-of-statements are repeated again and again. As soon as the condition becomes false { or true }, False Condition ? The exit condition True Statement 1 The loop body Statement 2 The interaction construct
  • 16. 3 Types of loops in C++  for Natural "counting" loop  do-while Least flexible Always executes loop body at least on  while Most flexible No “restrictions”
  • 17. For Loop Syntax for (Init_Action; Bool_Exp; Update_Action) Body_Statement Like if-else, Body_Statement can be a block statement
  • 18. For Loop Example for (count=0;count<3;count++) { cout << "Hi "; // Loop Body } How many times does loop body execute? Initialization, loop condition and update all "built into" the for-loop structure! A natural "counting" loop
  • 20. While Loop Example Consider: count = 0; // Initialization while (count < 3) // Loop Condition { cout << "Hi "; // Loop Body count++; // Update expression } Loop body executes how many times?
  • 21. Do while Loop Syntax
  • 22. Do while Loop Example count = 0; // Initialization do { cout << "Hi "; // Loop Body count++; // Update expression } while (count < 3); // Loop Condition Loop body executes how many times? do-while loops always execute body at least once!
  • 23. Loop Issues Loop’s condition expression can be ANY boolean expression. Examples: while (count<3 && done!=0) { // Do something } for (index=0;index<10 && entry!=-99) { // Do something }
  • 24. Loop Pitfalls: Misplaced ; Watch the misplaced ; (semicolon) Example: while (response != 0) ; { cout << "Enter val: "; cin >> response; } Notice the ";" after the while condition! Result here: INFINITE LOOP!
  • 25. Loop Pitfalls: Infinite Loops Loop condition must evaluate to false at some iteration through loop If not  infinite loop. Example: while (1) { cout << "Hello "; } A perfectly legal C++ loop  always infinite!
  • 26. The break and continue Statement Flow of Control Recall how loops provide "graceful" and clear flow of control in and out In RARE instances, can alter natural flow break; Forces loop to exit immediately. continue; Skips rest of loop body These statements violate natural flow Only used when absolutely necessary!
  • 27. Nested Loops Recall: ANY valid C++ statements can be inside body of loop This includes additional loop statements! Called "nested loops" Requires careful indenting: for (outer=0; outer<5; outer++) for (inner=7; inner>2; inner--) cout << outer << inner; Notice no { } since each body is one statement Good style dictates we use { } anyway