Shape logic 1

10
CS111 Lab Nested loop logic Instructor: Michael Gordon

description

 

Transcript of Shape logic 1

Page 1: Shape logic 1

CS111 Lab Nested loop logic

Instructor: Michael Gordon

Page 2: Shape logic 1

Conceptualize

Think of your printing space as a grid with

rows and columns

1 2 3

1 * * *

2 * * *

3 * * *

0 1 2

0 * * *

1 * * *

2 * * *

Page 3: Shape logic 1

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 3

1 *

2 * *

3 * * *

1 2 3 4

1 *

2 * *

3 * * *

4 * * * *

Page 4: Shape logic 1

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;

}

Page 5: Shape logic 1

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

middle = n/2+1

1 2 3

1 *

2 *

3 *

1 2 3 4 5

1 *

2 *

3 *

4 *

5 *

Page 6: Shape logic 1

Isosceles Triangle

The first thing you may notice

about this “triangle” is that it

doesn’t start at the top of the

grid. For the sake of space

(and other considerations)

let’s try to figure out (given the number of

columns) how many rows we need.

1 2 3

1

2 *

3 * * *

Page 7: Shape logic 1

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 4 5

1

2

3 *

4 * * *

5 * * * * *

1 2 3

1

2 *

3 * * *

Page 8: Shape logic 1

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.

0 1 2

0 *

1 *

2 *

1 2 3

1 *

2 *

3 *

Page 9: Shape logic 1

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 2 3 4

0 *

1 * * *

2 * * *

Page 10: Shape logic 1

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 2 3 4

0 *

1 * * *

2 * * * * *