Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Shape logic 1

664 views

Published on

  • Be the first to comment

  • Be the first to like this

Shape logic 1

  1. 1. CS111 Lab Nested loop logic Instructor: Michael Gordon
  2. 2. Conceptualize Think of your printing space as a grid with rows and columns 0 1 2 0 * * * * 1 * * * * 2 * * * 1 2 3 1 * * * 2 * * 3 * *
  3. 3. Simple right triangle  Where does a star appear?  1,1; 2,1; 2,2; 3,1; 3,2; 3,3  In each row, the col # with a star starts at 1 and goes until the row #.  The same logic applies for a larger grid. 1 2 1 * 2 * * 3 * 3 * 1 2 * 3 1 * 2 * * 3 * * * 4 * * * 4 *
  4. 4. Simple right triangle  Rows go from 1 to n.  On each row we output a star in each column until column equals row. for(int r=1; r<=n; r++){ for(int c=1;c<=r;c++){ cout<<“*”; } cout<<endl; }
  5. 5. Finding the middle  You don’t know what input size the user will give, so how will you know where the middle is?  If n=3, then the middle is 2  If n=5, then the middle is 3 1 2 3  middle = n/2+1 1 * 1 2 3 2 * 1 * 3 * 2 * 4 * 3 * 5 * 4 5
  6. 6. Isosceles Triangle  The first thing you may notice 1 2 about this “triangle” is that it 1 doesn’t start at the top of the 2 * grid. For the sake of space 3 * * (and other considerations) let’s try to figure out (given the number of columns) how many rows we need. 3 *
  7. 7. Column-to-row ratio 3 columns: 2 rows  5 columns: 3 rows  7 columns: 4 rows (not shown)  rows = columns/2 + 1  (same formula as finding the middle) 1 2 3 1 2 * 3 * 1 2 * 3 * 4 5 1 2 3 * 4 5 * * * * * * * *
  8. 8. Starting at Zero  We often start our rows and columns at zero instead of one.  In that case, the formula for the middle would be: mid = n/2 instead of n/2+1  At right: n = 3. 3/2=1 (int div) and 1 is the middle column. 1 2 1 * 2 * 3 3 * 0 1 0 * 1 * 2 * 2
  9. 9. Center+diagonals for (int r = 0; r <= rows; r++) { for (int c = 0; c <= cols; c++) { if (c==cntr+r || c==cntr-r || c==cntr) cout << "*"; else cout << " "; } 0 1 0 3 4 * 1 2 2 * * * * * *
  10. 10. Center+diagonals for (int r = 0; r <= rows; r++) { for (int c = 0; c <= cols; c++) { if (c>=cntr-r && c<=cntr+r) cout << "*"; else cout << " "; } cout<<endl; } 0 1 0 3 4 * 1 2 2 * * * * * * * *

×