Help! (Beginner)

Discussion in 'C Programming' started by aliplayer1, Nov 29, 2019.

  1. aliplayer1

    aliplayer1

    Joined:
    Nov 29, 2019
    Messages:
    1
    Likes Received:
    0
    Hello. Could anyone tell me why does the code below not run properly? I intended to print a pyramid using * but the output is strange.
    Code (C):
    #include <stdio.h>
    int main ( )
    {
        int i , j , rows ;


        printf("Enter the number of rows:");
        scanf("%d", &rows);

        for ( i = 1 ; i <= rows ; i++);
        {
            for ( j = 1 ; j <= rows - i ; j++)
                printf("  ");

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

            printf("\n");
        }
    }
     
    For example, if I run this code and give "rows" a value of 5 it outputs 11 stars one after each other. Help me, please.
     
    aliplayer1, Nov 29, 2019
    #1
    1. Advertisements

  2. aliplayer1

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    137
    Likes Received:
    16
    Location:
    Malaysia
    Can you show the output?
     
    John Joe, Dec 5, 2019
    #2
    1. Advertisements

  3. aliplayer1

    Commodore

    Joined:
    Jan 22, 2020
    Messages:
    2
    Likes Received:
    0
    Hello aliplayer1,

    Well, the output is strange due to the semicolon that you wrote in the first "for loop". If you quit that semicolon, the output will be the desired one.

    Should be this way (without modifying the rest of parts of your code):

    Code (Text):
    #include <stdio.h>
    int main ( )
    {
        int i , j , rows ;


        printf("Enter the number of rows:");
        scanf("%d", &rows);

        for ( i = 1 ; i <= rows ; i++)
        {
            for ( j = 1 ; j <= rows - i ; j++)
                printf("  ");

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

            printf("\n");
        }
    }
     
    Commodore, Jan 22, 2020
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.