Troy
Troy

Reputation: 65

C - print star pattern in different arrangement

My homework needs to print out the star pattern by using for loop as below:

!!!!!
!!!!
!!!
!!
!

Here is my loop:

    int i, j;
    for(i=5;i<=1;i--)
    {
        for(j=1;j<=i;j++)
        {
            printf("!");
        }
        printf("\n");
    }

Actually I have succeeded to print out the pattern as below already:

! 
!! 
!!! 
!!!! 
!!!!!

By the following loop:

    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=1;j<=i;j++)
        {
            printf("!");
        }
        printf("\n");
    }

Now I am confused why pattern 1 can't be printed, as there are no errors found. Also the output window will get down when I go ahead to run the program.

My Xcode is Ver 4.4.1

Upvotes: 1

Views: 2028

Answers (3)

MOHAMED
MOHAMED

Reputation: 43518

error in the loop in the stop condition. Use

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

instead of:

for(i=5;i<=1;i--)

Upvotes: 1

DrummerB
DrummerB

Reputation: 40211

In your first code sample you write the following:

for(i=5;i<=1;i--)

This for loop will never be entered. At the beginning i is set to 5. Then i<=1 is tested, which will return false and the for loop is skipped.

You should do this instead:

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

Upvotes: 2

Cyrille
Cyrille

Reputation: 25144

This loop cannot execute anything :

for(i=5;i<=1;i--)

It says "start with i = 5, and while i <= 1; do i--".

At the first iteration, i is already > 1, so your loop doesn't even enter.

What you should do is reverse the condition:

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

This way, you'll loop by starting with i = 5, and perform i-- while i >= 1.

General rule of thinking for a for loop :

for (A; B; C)
{
    D;
}

is equivalent to

A;
while (B)
{
    C;
    D;
}

Upvotes: 6

Related Questions