marija
marija

Reputation: 51

Drawing a triangle using a for loop

Here's my problem. Using only the characters * and +you need to form rectangular image with width m and height n (m < n) that depicts a right isosceles triangle with character + inside the rectangle made of characters * (view examples). For each m and n read from standard input your program should output the correct image. Attention: Do not print unnecessary empty spaces or new line characters. Note: The correct solution of the problem is without the usage of arrays/matrices since there is no limit on m and n. Clearance: The triangle is formed with one character + at the beginning of the first row, two at the beginning of the second row,... m characters + at the beginning of the m-th row. Here's an example of what it should look like for the input 3 and 4 http://prntscr.com/53xv5s

#include <stdio.h>

int main ()
{
int m, n, i, j;
scanf ("%d %d", &m, &n);
for (i=0; i<m; i++)
{
    printf ("+");
    for (j=n-1; j>0; j--)
    {
        printf ("*");            
    }
    printf ("\n");    
}    
return 0;
}

Any help on how to fix it? So far what I get is this http://prntscr.com/53xvq2

Upvotes: 2

Views: 4281

Answers (2)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

#include <stdio.h>

int main () {
    int row, column, rowCount, columnCount;

    printf("Enter row and column length: \n>");
    scanf (" %d %d", &row, &column);

    for (rowCount = 0; rowCount < row; rowCount++) {

        for (columnCount = 0; columnCount < column; columnCount++) {

            if(columnCount <= rowCount)
                printf ("+");
            else
                printf ("*");
        }

        printf ("\n");
    }

    return 0;

}

Upvotes: 1

Ed Smilovici
Ed Smilovici

Reputation: 304

try:

#include <stdio.h>
int main ()
{
int m, n, i, j;
scanf ("%d %d", &m, &n);
for (i=0; i<m; i++)
{
    for (j=0; j<n; j++)
    {
        if(j <= i)
            printf ("+");
        else
            printf ("*");
    }
    printf ("\n");
}
return 0;
}

This way it will always print n chars and n lines every line will start with i +'s and end with *

Upvotes: 0

Related Questions