SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Chapter 6 – Iteration
Iterative structures, or looping structures, are used in programming to
repeat sections of code. Examples where iteration is important:
• Calculating f(x) for 100 values of x
• Computing a result iteratively until a certain accuracy is reached, such
  as in evaluating a series like sin(x) = x – x3/3! + x5/5! – x7/7! + ….
• Printing a table of results
• Allowing the user to correct input values or to rerun a program
• Reading large quantities of data from a data file
• Working with arrays
• Etc

There are three basic types of control structures:
• Sequential structures (or straight-line structures)
• Decision structures (or selection structures or branching structures)
• Iterative structures (or looping structures)
These structures are illustrated on the following page:               1
Flowcharts for sequential, selection, and iterative control structures



   Command                           Command                          Command



   Command
                            False      Test       True                  Setup      Done


   Command              Commands                 Commands
                        to execute               to execute
                          if False                 if True           Commands
   Command



   Command                           Command                          Command



Sequential Structure             Example Selection Structure       Iterative Structure
                                                                                     2
(straight-line structure)      (decision or branching structure)   (looping structure)
Iterative Structures in C++
There are three types of iterative structures in C++:
• while loop
   – Continue looping while a condition is true
   – Pre-test on the condition, so loop is executed 0 or more times
• do-while loop
   – Continue looping while a condition is true
   – Post-test on the condition, so loop is executed 1 or more times
• for loop
   – Loop for a specific number of iterations based on an index variable
while loop
Key features:
• A pre-test is used at the beginning of the loop
• The loop is executed 0 or more times (until the condition is false)
• The test condition must be initialized before the loop



  Form:                        Example 1: while loop

  while (condition)            int i = 1;
  {                            while (i <= 5)
         statement(s)          {
  }                                    cout << “Loop #” << i << endl;
                                       i++;
  Note: braces optional        }
  if only one statement.
Example 2: while loop
Example 3: while loop
Write a C++ program to calculate the average of an unknown number of
grades as follows:
•   Prompt the user to enter a grade each time through the loop
•   Update the sum and number of grades
•   Prompt the user to enter a negative grade after the last valid grade
•   Continue looping while the input grade is not negative
Example 4: while loop
Write a C++ program to evaluate e (the base of the natural log) to 5
digits after the decimal point using the following series:
                 e = 1/0! + 1/1! + 1/2! + 1/3! + …..
Display the final value of e (it should be 2.71828).
do while loop
Key features:
• A post-test is used at the end of the loop
• The loop is executed 1 or more times (until the condition is false)
• The loop must be executed at least once!
• It is not necessary to initialize a test condition before the loop
• Unlike the while loop, there is a semicolon after the condition.
  Form:
  do
  {
          statement(s)
  }
  while (condition);

  Note: braces optional
  if only one statement.
Example 1: do while loop – re-running a program
Example 2: do while loop
Write a C++ program to determine the smallest integer N such that
       N3 – 2N2 > 100,000
Display the result.
for loop
• Often the best loop structure when you know how many times the
  instructions in the loop are to be executed.
• The for loop has three parts:
   – Initialization expression – a loop control variable is assigned an initial value
   – Conditional statement – the loop is repeated as long as this is true
   – Step – specifies how to modify the loop variable after each pass thru the loop
• Form:
     for (initialization expression; conditional statement; step)
     {
             statement(s)
     }
    Note: braces optional if only one statement.
 For loop – Example 1:
 for (i = 1; i <= 10; i++)
 {                                                      Result: “Hello!” is
           cout << “Hello!” << endl;                    displayed ten times.
 }
for loop – Example 2
Display sin(α) for α = 0 to 90° to 10° steps.
for loop – Example 3                                 20
Display the result of the following summation: Sum = ∑ n 3
                                                    n =1
for loop – Example 4
Determine the output in each case below:




                                           LoopCount = _______

                                           LoopCount = _______

                                           LoopCount = _______

                                           LoopCount = _______

                                           LoopCount = _______
for loop – Example 5
Find the average of 100 grades in a data file.
Nested for loops
There are many cases where it is useful to form nested loops, or loops
inside or other loops. An example is illustrated below:


  for (int i = 1; i < = 4; i++)
  {
     statement(s)
     for (int j = 1; j <= 3; j++)
                                                     Outer loop
     {                                 Inner loop
          statement(s)
     }
     statement(s)
  }
Tracing through nested for loops
It is often necessary to trace through a nested loop structure to
determine the resulting calculations, displayed values, etc. Using a
table can be helpful.
Example: Trace through the nested loop shown below:

  for (int i = 1; i < = 4; i++)            i          j         k
  {
     for (int j = 1; j <= 3; j++)
     {
          k = i + j;
     }
  }
Nested for loops – Example 1
Determine the output for each part below.
   int Count = 0;
   for (int i = 1; i < = 5; i++)
       for (int j = 1; j <= 4; j++)              Count = __________
               for (int k = 1; k <= 3; k++)
                         Count++;
   cout << “Count = “ << Count;

   int Count1 = 0, Count2 = 0, Count3 = 0;
   for (int i = 10; i > = 0; i-=2)
   {
       Count1++;
       for (int j = 3; j <= 24; j+=3)            Count1 = __________
       {
              Count2++;
              for (int k = -20; k <= 20; k+=5)   Count2 = __________
                         Count3++;
       }
   }                                             Count3 = __________
   cout << “Count1 = “ << Count1 << endl;
   cout << “Count1 = “ << Count1 << endl;
   cout << “Count1 = “ << Count1 << endl;
Nested for loops – Example 2
Determine the output for the instructions shown below.

 for (int i = 1; i < = 2; i++)
     for (int j = i; j <= 3; j++)
             for (int k = j; k <= 4; k++)
                        cout << i << j << k << endl;


                                                       Output:
Nested for loops – Example 3
Data file datex3.in contains 100 numbers with 10 numbers in each
row. Determine the sum of the values in each row.
Infinite loops (forever loops)
It is sometimes useful to construct a loop which will execute forever.
Such loops are sometimes called infinite loops or forever loops.
Examples:
• Monitor an alarm system 24 hours per day and sound an alarm when
  appropriate
• Run the display on a gas pump and display advertising until a user
  presses a button to indicate that they want to pump gas.

Notes:
• An infinite loop may be exited at any point using a break statement.
• You can generally stop an infinite loop from the keyboard by
  pressing Ctrl+C.
Infinite loops (forever loops) – form
Infinite loops can be created easily using any of the three types of
loop structures introduced:

Infinite while loop:       while (1)
                           {
                             statement(s)
                           }
Infinite do while loop:
                           do
                           {
                                statement(s)
                           }
                           while (1);
Infinite for loop:         for(;;)
                           {
                              statement(s)
                           }
Infinite loops - examples        //clock program
                                 while (1)
                                 {
                                    statements to display time
                                 }
 // alarm program
 do
 {
     statements to sound alarm if certain inputs occur
 }
 while (1);
                              // vending machine
                              for(;;)
                              {
                                  statements to wait for inputs
                                  statements to release product
                                  statements to dispense change
                              }
Structures with an indeterminate number of loops
For loops with an indeterminate number of iterations, we can use:
 – Do while loop – exit at the top of the loop
 – While loop – exit at the bottom of the loop
 – Forever loop – exit in the middle of the loop using a break statement


   while (x < 2)           do                     for(;;)
   {                       {                      {
     statement(s)               statement(s)         statement(s)
   }                       }                         if (!(x<2)) break;
                           while (x < 2);            statement(s)
 Exit from top of loop
   once x<2 is false                              }
                          Exit from bottom of
                         loop once x<2 is false    Exit from middle of
                                                  loop once x<2 is false

      Note: Any number of exit points could be provided in
      any of the loop structures above using break statements.
Forever loop - Example
Write a C++ program to evaluate e (the base of the natural log) using the
infinite series e = 1/0! + 1/1! + 1/2! + 1/3! + ….. accurate to 8 digits
after the decimal point using a forever loop with a break statement.
Graphing in C++
Generating graphs in C++ is a fairly advanced topic. However, it is easy
to write a C++ program to send the x,y data to a data file where it can
then be graphed using other programs like Excel or MatLab.
Excel can easily open data files where columns of numbers are separated
by commas, spaces, or tabs. If they are separated by commas, the file is
sometimes called a “commas delimited file.”

                                    Commas delimited
                                    data file A:xydata.dat
 C++ Program                                                 Excel
 …                                         10,125        y
 Ofstream OutData(“A:xydata.dat”)          12,137
 //calculate x and y values                14,156
 …                                         16,189
 OutData << x << “,” << y << endl;         18, 211                   x
 …                                         …
Example: Graphing in C++
Graph the function y = 100e-x for x = 0.0, 0.2, 0.4, … , 5.0
Example: Graphing in C++
•   Open the data file A:OutToExcel.dat with Excel (select All Files
    (*.*) for File Type.
•   The Text Import Wizard (Step 1 of 3) should appear as shown below.
     The default is a delimited file. Select Next to continue.
•   The Text Import Wizard (Step 2 of 3) should appear next. Select
    Comma as the delimiter (default is Tab). Select Next to continue.
Example: Graphing in C++
•   The Text Import Wizard (Step 3 of 3) should appear next. This
    screen lets you select data format. The default is General which is
    sufficient for this example. Select Finish .
•   The data should now appear in columns A and B in Excel. Add the
    graph.

Weitere ähnliche Inhalte

Was ist angesagt?

Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsMohamed Loey
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programmingChitrank Dixit
 
What is an algorithm?
What is an algorithm?What is an algorithm?
What is an algorithm?Angela DeHart
 
for loop in java
for loop in java for loop in java
for loop in java Majid Ali
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchartRabin BK
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 
Control structures repetition
Control structures   repetitionControl structures   repetition
Control structures repetitionOnline
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Algorithm and pseudo codes
Algorithm and pseudo codesAlgorithm and pseudo codes
Algorithm and pseudo codeshermiraguilar
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Programming Fundamentals lecture 1
Programming Fundamentals lecture 1Programming Fundamentals lecture 1
Programming Fundamentals lecture 1REHAN IJAZ
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Visual Basic Programming
Visual Basic ProgrammingVisual Basic Programming
Visual Basic ProgrammingOsama Yaseen
 
Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Vibhawa Nirmal
 

Was ist angesagt? (20)

Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
 
What is an algorithm?
What is an algorithm?What is an algorithm?
What is an algorithm?
 
for loop in java
for loop in java for loop in java
for loop in java
 
Number system conversion
Number system conversionNumber system conversion
Number system conversion
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Control structures repetition
Control structures   repetitionControl structures   repetition
Control structures repetition
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Hashing
HashingHashing
Hashing
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Algorithm and pseudo codes
Algorithm and pseudo codesAlgorithm and pseudo codes
Algorithm and pseudo codes
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Programming Fundamentals lecture 1
Programming Fundamentals lecture 1Programming Fundamentals lecture 1
Programming Fundamentals lecture 1
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Break and continue
Break and continueBreak and continue
Break and continue
 
Visual Basic Programming
Visual Basic ProgrammingVisual Basic Programming
Visual Basic Programming
 
Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners
 

Andere mochten auch

Control structures selection
Control structures   selectionControl structures   selection
Control structures selectionOnline
 
Dynamics Behaviour of Multi Storeys Framed Structures by of Iterative Method
Dynamics Behaviour of Multi Storeys Framed  Structures by of Iterative Method Dynamics Behaviour of Multi Storeys Framed  Structures by of Iterative Method
Dynamics Behaviour of Multi Storeys Framed Structures by of Iterative Method AM Publications
 
Ndu06 typesof language
Ndu06 typesof languageNdu06 typesof language
Ndu06 typesof languagenicky_walters
 
2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problem2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problemFrankie Jones
 
Jumping statements
Jumping statementsJumping statements
Jumping statementsSuneel Dogra
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
5 problem solving with the sequential logic structure
5 problem solving with the sequential logic structure5 problem solving with the sequential logic structure
5 problem solving with the sequential logic structureRheigh Henley Calderon
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C ProgrammingKamal Acharya
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solvingKhan Yousafzai
 
Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statementspragya ratan
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual BasicTushar Jain
 

Andere mochten auch (20)

Control structures selection
Control structures   selectionControl structures   selection
Control structures selection
 
Debugging Debugging
Debugging DebuggingDebugging Debugging
Debugging Debugging
 
Dynamics Behaviour of Multi Storeys Framed Structures by of Iterative Method
Dynamics Behaviour of Multi Storeys Framed  Structures by of Iterative Method Dynamics Behaviour of Multi Storeys Framed  Structures by of Iterative Method
Dynamics Behaviour of Multi Storeys Framed Structures by of Iterative Method
 
Ndu06 typesof language
Ndu06 typesof languageNdu06 typesof language
Ndu06 typesof language
 
2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problem2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problem
 
Jumping statements
Jumping statementsJumping statements
Jumping statements
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
5 problem solving with the sequential logic structure
5 problem solving with the sequential logic structure5 problem solving with the sequential logic structure
5 problem solving with the sequential logic structure
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Using loops
Using loopsUsing loops
Using loops
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving
 
7 problem solving with loops
7 problem solving with loops7 problem solving with loops
7 problem solving with loops
 
6 problem solving with decisions
6 problem solving with decisions6 problem solving with decisions
6 problem solving with decisions
 
Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statements
 
business data processing
business data processingbusiness data processing
business data processing
 
Basics of information technology
Basics of information technologyBasics of information technology
Basics of information technology
 
File organization
File organizationFile organization
File organization
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
 
Loops in C
Loops in CLoops in C
Loops in C
 

Ähnlich wie Iteration

Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
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 KRKrishna Raj
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languagetanmaymodi4
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languageTanmay Modi
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.pptsanjay
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loopsManzoor ALam
 

Ähnlich wie Iteration (20)

Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
06.Loops
06.Loops06.Loops
06.Loops
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
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
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
06 Loops
06 Loops06 Loops
06 Loops
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
Loops c++
Loops c++Loops c++
Loops c++
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 

Mehr von Liam Dunphy

Butterfly Struggles - An inspirational life lesson
Butterfly Struggles - An inspirational life lessonButterfly Struggles - An inspirational life lesson
Butterfly Struggles - An inspirational life lessonLiam Dunphy
 
Tm hills scarytasla-ming
Tm hills scarytasla-mingTm hills scarytasla-ming
Tm hills scarytasla-mingLiam Dunphy
 
Creative learning spaces
Creative learning spacesCreative learning spaces
Creative learning spacesLiam Dunphy
 
#ccGlobal for cesimeet
#ccGlobal for cesimeet#ccGlobal for cesimeet
#ccGlobal for cesimeetLiam Dunphy
 
Tm sydney north - collaboration
Tm sydney north - collaborationTm sydney north - collaboration
Tm sydney north - collaborationLiam Dunphy
 
Training presentation outlook 2007 manage your mailbox 3-move or copy message...
Training presentation outlook 2007 manage your mailbox 3-move or copy message...Training presentation outlook 2007 manage your mailbox 3-move or copy message...
Training presentation outlook 2007 manage your mailbox 3-move or copy message...Liam Dunphy
 
Training presentation outlook 2007 manage your mailbox 2-understand your choi...
Training presentation outlook 2007 manage your mailbox 2-understand your choi...Training presentation outlook 2007 manage your mailbox 2-understand your choi...
Training presentation outlook 2007 manage your mailbox 2-understand your choi...Liam Dunphy
 
Organising and dss steps in designing a spreadsheet solution
Organising and dss   steps in designing a spreadsheet solutionOrganising and dss   steps in designing a spreadsheet solution
Organising and dss steps in designing a spreadsheet solutionLiam Dunphy
 
Programming Languages
Programming LanguagesProgramming Languages
Programming LanguagesLiam Dunphy
 
Representational Tools
Representational ToolsRepresentational Tools
Representational ToolsLiam Dunphy
 
System Data Modelling Tools
System Data Modelling ToolsSystem Data Modelling Tools
System Data Modelling ToolsLiam Dunphy
 
Communications Systems
Communications SystemsCommunications Systems
Communications SystemsLiam Dunphy
 
Ipt Syllabus Changes Communications Systems
Ipt Syllabus Changes   Communications SystemsIpt Syllabus Changes   Communications Systems
Ipt Syllabus Changes Communications SystemsLiam Dunphy
 
Ipt Syllabus Changes
Ipt Syllabus ChangesIpt Syllabus Changes
Ipt Syllabus ChangesLiam Dunphy
 
Ipt Syllabus Changes Project Management
Ipt Syllabus Changes   Project ManagementIpt Syllabus Changes   Project Management
Ipt Syllabus Changes Project ManagementLiam Dunphy
 

Mehr von Liam Dunphy (20)

Butterfly Struggles - An inspirational life lesson
Butterfly Struggles - An inspirational life lessonButterfly Struggles - An inspirational life lesson
Butterfly Struggles - An inspirational life lesson
 
Tm hills scarytasla-ming
Tm hills scarytasla-mingTm hills scarytasla-ming
Tm hills scarytasla-ming
 
Creative learning spaces
Creative learning spacesCreative learning spaces
Creative learning spaces
 
#ccGlobal for cesimeet
#ccGlobal for cesimeet#ccGlobal for cesimeet
#ccGlobal for cesimeet
 
Tm sydney north - collaboration
Tm sydney north - collaborationTm sydney north - collaboration
Tm sydney north - collaboration
 
Training presentation outlook 2007 manage your mailbox 3-move or copy message...
Training presentation outlook 2007 manage your mailbox 3-move or copy message...Training presentation outlook 2007 manage your mailbox 3-move or copy message...
Training presentation outlook 2007 manage your mailbox 3-move or copy message...
 
Training presentation outlook 2007 manage your mailbox 2-understand your choi...
Training presentation outlook 2007 manage your mailbox 2-understand your choi...Training presentation outlook 2007 manage your mailbox 2-understand your choi...
Training presentation outlook 2007 manage your mailbox 2-understand your choi...
 
Mm expertise
Mm expertiseMm expertise
Mm expertise
 
Organising and dss steps in designing a spreadsheet solution
Organising and dss   steps in designing a spreadsheet solutionOrganising and dss   steps in designing a spreadsheet solution
Organising and dss steps in designing a spreadsheet solution
 
Programming Languages
Programming LanguagesProgramming Languages
Programming Languages
 
Meta Languages
Meta LanguagesMeta Languages
Meta Languages
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Algorithms2
Algorithms2Algorithms2
Algorithms2
 
Representational Tools
Representational ToolsRepresentational Tools
Representational Tools
 
System Data Modelling Tools
System Data Modelling ToolsSystem Data Modelling Tools
System Data Modelling Tools
 
Communications Systems
Communications SystemsCommunications Systems
Communications Systems
 
Ipt Syllabus Changes Communications Systems
Ipt Syllabus Changes   Communications SystemsIpt Syllabus Changes   Communications Systems
Ipt Syllabus Changes Communications Systems
 
Ipt Syllabus Changes
Ipt Syllabus ChangesIpt Syllabus Changes
Ipt Syllabus Changes
 
Ipt Syllabus Changes Project Management
Ipt Syllabus Changes   Project ManagementIpt Syllabus Changes   Project Management
Ipt Syllabus Changes Project Management
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 

Kürzlich hochgeladen

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
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
 
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
 
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
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
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
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
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
 

Kürzlich hochgeladen (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
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
 
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...
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
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
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 

Iteration

  • 1. Chapter 6 – Iteration Iterative structures, or looping structures, are used in programming to repeat sections of code. Examples where iteration is important: • Calculating f(x) for 100 values of x • Computing a result iteratively until a certain accuracy is reached, such as in evaluating a series like sin(x) = x – x3/3! + x5/5! – x7/7! + …. • Printing a table of results • Allowing the user to correct input values or to rerun a program • Reading large quantities of data from a data file • Working with arrays • Etc There are three basic types of control structures: • Sequential structures (or straight-line structures) • Decision structures (or selection structures or branching structures) • Iterative structures (or looping structures) These structures are illustrated on the following page: 1
  • 2. Flowcharts for sequential, selection, and iterative control structures Command Command Command Command False Test True Setup Done Command Commands Commands to execute to execute if False if True Commands Command Command Command Command Sequential Structure Example Selection Structure Iterative Structure 2 (straight-line structure) (decision or branching structure) (looping structure)
  • 3. Iterative Structures in C++ There are three types of iterative structures in C++: • while loop – Continue looping while a condition is true – Pre-test on the condition, so loop is executed 0 or more times • do-while loop – Continue looping while a condition is true – Post-test on the condition, so loop is executed 1 or more times • for loop – Loop for a specific number of iterations based on an index variable
  • 4. while loop Key features: • A pre-test is used at the beginning of the loop • The loop is executed 0 or more times (until the condition is false) • The test condition must be initialized before the loop Form: Example 1: while loop while (condition) int i = 1; { while (i <= 5) statement(s) { } cout << “Loop #” << i << endl; i++; Note: braces optional } if only one statement.
  • 6. Example 3: while loop Write a C++ program to calculate the average of an unknown number of grades as follows: • Prompt the user to enter a grade each time through the loop • Update the sum and number of grades • Prompt the user to enter a negative grade after the last valid grade • Continue looping while the input grade is not negative
  • 7. Example 4: while loop Write a C++ program to evaluate e (the base of the natural log) to 5 digits after the decimal point using the following series: e = 1/0! + 1/1! + 1/2! + 1/3! + ….. Display the final value of e (it should be 2.71828).
  • 8. do while loop Key features: • A post-test is used at the end of the loop • The loop is executed 1 or more times (until the condition is false) • The loop must be executed at least once! • It is not necessary to initialize a test condition before the loop • Unlike the while loop, there is a semicolon after the condition. Form: do { statement(s) } while (condition); Note: braces optional if only one statement.
  • 9. Example 1: do while loop – re-running a program
  • 10. Example 2: do while loop Write a C++ program to determine the smallest integer N such that N3 – 2N2 > 100,000 Display the result.
  • 11. for loop • Often the best loop structure when you know how many times the instructions in the loop are to be executed. • The for loop has three parts: – Initialization expression – a loop control variable is assigned an initial value – Conditional statement – the loop is repeated as long as this is true – Step – specifies how to modify the loop variable after each pass thru the loop • Form: for (initialization expression; conditional statement; step) { statement(s) } Note: braces optional if only one statement. For loop – Example 1: for (i = 1; i <= 10; i++) { Result: “Hello!” is cout << “Hello!” << endl; displayed ten times. }
  • 12. for loop – Example 2 Display sin(α) for α = 0 to 90° to 10° steps.
  • 13. for loop – Example 3 20 Display the result of the following summation: Sum = ∑ n 3 n =1
  • 14. for loop – Example 4 Determine the output in each case below: LoopCount = _______ LoopCount = _______ LoopCount = _______ LoopCount = _______ LoopCount = _______
  • 15. for loop – Example 5 Find the average of 100 grades in a data file.
  • 16. Nested for loops There are many cases where it is useful to form nested loops, or loops inside or other loops. An example is illustrated below: for (int i = 1; i < = 4; i++) { statement(s) for (int j = 1; j <= 3; j++) Outer loop { Inner loop statement(s) } statement(s) }
  • 17. Tracing through nested for loops It is often necessary to trace through a nested loop structure to determine the resulting calculations, displayed values, etc. Using a table can be helpful. Example: Trace through the nested loop shown below: for (int i = 1; i < = 4; i++) i j k { for (int j = 1; j <= 3; j++) { k = i + j; } }
  • 18. Nested for loops – Example 1 Determine the output for each part below. int Count = 0; for (int i = 1; i < = 5; i++) for (int j = 1; j <= 4; j++) Count = __________ for (int k = 1; k <= 3; k++) Count++; cout << “Count = “ << Count; int Count1 = 0, Count2 = 0, Count3 = 0; for (int i = 10; i > = 0; i-=2) { Count1++; for (int j = 3; j <= 24; j+=3) Count1 = __________ { Count2++; for (int k = -20; k <= 20; k+=5) Count2 = __________ Count3++; } } Count3 = __________ cout << “Count1 = “ << Count1 << endl; cout << “Count1 = “ << Count1 << endl; cout << “Count1 = “ << Count1 << endl;
  • 19. Nested for loops – Example 2 Determine the output for the instructions shown below. for (int i = 1; i < = 2; i++) for (int j = i; j <= 3; j++) for (int k = j; k <= 4; k++) cout << i << j << k << endl; Output:
  • 20. Nested for loops – Example 3 Data file datex3.in contains 100 numbers with 10 numbers in each row. Determine the sum of the values in each row.
  • 21. Infinite loops (forever loops) It is sometimes useful to construct a loop which will execute forever. Such loops are sometimes called infinite loops or forever loops. Examples: • Monitor an alarm system 24 hours per day and sound an alarm when appropriate • Run the display on a gas pump and display advertising until a user presses a button to indicate that they want to pump gas. Notes: • An infinite loop may be exited at any point using a break statement. • You can generally stop an infinite loop from the keyboard by pressing Ctrl+C.
  • 22. Infinite loops (forever loops) – form Infinite loops can be created easily using any of the three types of loop structures introduced: Infinite while loop: while (1) { statement(s) } Infinite do while loop: do { statement(s) } while (1); Infinite for loop: for(;;) { statement(s) }
  • 23. Infinite loops - examples //clock program while (1) { statements to display time } // alarm program do { statements to sound alarm if certain inputs occur } while (1); // vending machine for(;;) { statements to wait for inputs statements to release product statements to dispense change }
  • 24. Structures with an indeterminate number of loops For loops with an indeterminate number of iterations, we can use: – Do while loop – exit at the top of the loop – While loop – exit at the bottom of the loop – Forever loop – exit in the middle of the loop using a break statement while (x < 2) do for(;;) { { { statement(s) statement(s) statement(s) } } if (!(x<2)) break; while (x < 2); statement(s) Exit from top of loop once x<2 is false } Exit from bottom of loop once x<2 is false Exit from middle of loop once x<2 is false Note: Any number of exit points could be provided in any of the loop structures above using break statements.
  • 25. Forever loop - Example Write a C++ program to evaluate e (the base of the natural log) using the infinite series e = 1/0! + 1/1! + 1/2! + 1/3! + ….. accurate to 8 digits after the decimal point using a forever loop with a break statement.
  • 26. Graphing in C++ Generating graphs in C++ is a fairly advanced topic. However, it is easy to write a C++ program to send the x,y data to a data file where it can then be graphed using other programs like Excel or MatLab. Excel can easily open data files where columns of numbers are separated by commas, spaces, or tabs. If they are separated by commas, the file is sometimes called a “commas delimited file.” Commas delimited data file A:xydata.dat C++ Program Excel … 10,125 y Ofstream OutData(“A:xydata.dat”) 12,137 //calculate x and y values 14,156 … 16,189 OutData << x << “,” << y << endl; 18, 211 x … …
  • 27. Example: Graphing in C++ Graph the function y = 100e-x for x = 0.0, 0.2, 0.4, … , 5.0
  • 28. Example: Graphing in C++ • Open the data file A:OutToExcel.dat with Excel (select All Files (*.*) for File Type. • The Text Import Wizard (Step 1 of 3) should appear as shown below. The default is a delimited file. Select Next to continue. • The Text Import Wizard (Step 2 of 3) should appear next. Select Comma as the delimiter (default is Tab). Select Next to continue.
  • 29. Example: Graphing in C++ • The Text Import Wizard (Step 3 of 3) should appear next. This screen lets you select data format. The default is General which is sufficient for this example. Select Finish . • The data should now appear in columns A and B in Excel. Add the graph.