Goush
Goush

Reputation: 27

Unwanted newline appearing

Whenever I run my program, it doesn't start printing the asterisks until after a newline, why? Here is my code:

int main()
{
    int createRow = 0,
        createCol;

    while (createRow <= 5)
    {
        while (createCol <= ((createRow * 2) - 1))
        {
            printf("*");
            createCol++;
        }
        createCol = 1;
        createRow++;

        printf("\n");
    }
    return 0;
}

Output:

*
***
*****
*******
*********
***********
*************
***************
*****************
*******************

As you see, right before the very first asterisk, there is a newline. How do I fix this?

Upvotes: 2

Views: 63

Answers (2)

Charles
Charles

Reputation: 4362

You can remove it by changing

printf("\n");

to

createRow == 1 ?: printf("\n");

This is the same as the following, but is more concise and makes sense to a programmer who knows how to use the ternary operator.

if (createRow != 1) {
   printf("\n");
}

When using the ternary operator condition ? expression1 : expression2; expression1 is not required but expression2 is. Expression1 executes if the condition is true and expression2 executes if the condition is false.

Upvotes: 2

haccks
haccks

Reputation: 106112

createCol is uninitialized and used before it is assigned a value.

Do the following changes

int createRow = 1,
    createCol = 0;  

while (createRow <= 5)
{
    while (createCol <= ((createRow * 2)-1))
    {
       //Loop body
    }
    createCol = 0;
    // Rest of the code
}

Upvotes: 3

Related Questions