Nested Loops and Stepwise Refinement - PowerPoint PPT Presentation

1 / 6
About This Presentation
Title:

Nested Loops and Stepwise Refinement

Description:

ICE: Nested Loops to Generate a Right Triangle ... nested for loops to generate a right triangle with n asterisks such that the ... – PowerPoint PPT presentation

Number of Views:75
Avg rating:3.0/5.0
Slides: 7
Provided by: need9
Category:

less

Transcript and Presenter's Notes

Title: Nested Loops and Stepwise Refinement


1
Nested Loops and Stepwise Refinement
for(int row 1 row lt n row) for(int
col 1 col lt n col) // deal with
each row of matrix col by col // end for col
// end for row
  • Nested Loops
  • Loops defined
    inside the

    blocks of loops
    are referred to

    as "nested".
  • A way to deal with the complexities of writing
    programs using nested loops is to follow the
    design paradigm of stepwise refinement
  • write pseudo-programs in rough (highly abstract)
    steps
  • continually refine steps until they end up as
    actual C code that solve problem. Remember to
    compile often!

2
Example Hankel Matrix
  • A Hankel matrix often used for statistical
    analysis is a matrix in which the (i,j)th entry
    depends only on
    the sum ij.
  • The Hankel matrix defined by the numbers
    1, 2, ..., 2n-1 is
  • Consider a program that reads in a value n (less
    than 50) from the user and print out the Hankel
    matrix defined by 1, 2, ..., 2n-1 to the screen

1 2 3 ... n 2 3 4 ... n1 ... n n1 n2 ...
2n-1
3
Hankel Matrix Stepwise Refinement
  • With stepwise refinement, 1st consider the
    problem from a highly abstract viewpoint
  • Get a value for n, then
  • compute Hankel matrix
  • Gradually refine each abstraction

4
Completed Hankel Solution
  • Continue Refinement until all abstract concepts
    are concretely represented in the code

5
ICE Trace this programs output
  • include ltiostreamgt
  • using namespace std
  • int main()
  • int n, i
  • for (n2 nlt4 n)
  • for (i7 igt6 i--)
  • cout ltlt n ltlt " " ltlt i ltltendl
  • cout ltlt "i is now " ltlt i ltlt endl
  • // for n
  • cout ltlt "n is now " ltlt n ltlt endl
  • return 0

6
ICE Nested Loops to Generate a Right Triangle
  • Write a program that uses nested for loops to
    generate a right triangle with n asterisks such
    that the first row has one asterisk, the second
    has two, and so on.
  • Right-align the asterisks on each row such as
Write a Comment
User Comments (0)
About PowerShow.com