Your SlideShare is downloading. ×
Shape logic 1
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Shape logic 1

454
views

Published on


0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
454
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. CS111 Lab Nested loop logic Instructor: Michael Gordon
  • 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. 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. 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. 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. 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. 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. 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. 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. 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 * * * * * * * *