belle - 8 months ago 31

C Question

I am sorry if this is such a basic question, but i've been working on this problem for hours.

The code below prints an inverted triangle based on input rows.

How can i edit this code to draw an inverted triangle based on input base LENGTH?

I.E.:

Input base length= 5

`***** //five characters here`

***

*

I somehow cant come up with a formula without messing up the pattern.

this is the code im trying to edit,

`#include<stdio.h>`

int main()

{

int rows, i, j, space;

printf("Enter the number of rows: ");

scanf("%d",&rows);

for(i=rows; i>=1; --i)

{

for(space=0; space < rows-i; ++space)

printf(" ");

for(j=i; j <= 2*i-1; ++j)

printf("*");

for(j=0; j < i-1; ++j)

printf("*");

printf("\n");

}

return 0;

}

Which give me output

input rows= 5

`********* // 5 ROWS of characters`

*******

*****

***

*

thank you!

Answer

If you can print the rows using your program, you could derive a small formula to convert the base length to the the number of rows as follows =>

**TL;DR:**

Use the following formula:

```
BaseLength = (2 * NumberOfRows ) -1
```

**Long Version:**

First we see that with every row, the base length is always an odd number. Additionally with the addition of every row, the base length forms an Arithmetic Progression (AP) with a difference of 2, e.g. If number of rows is 2, then the base length is 3. If number of rows is 3, then the base length is 5.

As you can see, the row count forms an AP with difference 1 =>

```
1, 2, 3, 4, ...
```

Correspondingly, the base length forms the AP with difference 2 =>

```
1, 3, 5, 7 ...
```

Therefore, we can calculate the n(th) element in the base length AP as follows =>

```
T(n) = a + (n - 1)*d
```

Where `a`

is the first element in the series, and `d`

is the difference between the elements in the series. Plug in the values `a = 1`

, `d = 2`

```
T(n) = 1 + (n - 1)*2 = 2n -1
```

Notice here, that `n`

represents the number of rows, `T(n)`

represents the base length, implying that the relation becomes =>

```
BaseLength = (2 * NumberOfRows ) -1
```

Therefore, if you input `BaseLength = 9`

, you get `NumberOfRows = 5`

.

You can use this formula in your code to convert the base length to number of rows, whilst keeping the core functionality (i.e. printing rows of *) exactly the same.

Source (Stackoverflow)