开发者

Displaying an inverted pyramid of asterisks

开发者 https://www.devze.com 2022-12-25 01:50 出处:网络
I help with my program. I am required to create a inverted pyramid of stars which rows depends on the number o开发者_运维技巧f stars the user keys, but I\'ve done it so it does not give an inverted py

I help with my program. I am required to create a inverted pyramid of stars which rows depends on the number o开发者_运维技巧f stars the user keys, but I've done it so it does not give an inverted pyramid, it gives a regular pyramid.

#include <stdio.h>
#include <conio.h>
void printchars(int no_star, char space);
int getNo_of_rows(void);
int main(void)
{
    int numrows, rownum;
    rownum=0;
    numrows=getNo_of_rows();
    for(rownum=0;rownum<=numrows;rownum++)
    {
        printchars(numrows-rownum, ' ');
        printchars((2*rownum-1), '*');
        printf("\n");
    }
    _getche();
    return 0;
}

void printchars(int no_star, char space)
{
    int cnt;
    for(cnt=0;cnt<no_star;cnt++)
    {
        printf("%c",space);
    }
}

int getNo_of_rows(void)
{
    int no_star;
    printf("\n Please enter the number of stars you want to print\n");

    scanf("%d",&no_star);
    while(no_star<1)
    {
        printf("\n number incorrect, please enter correct number");
        scanf("%d",&no_star);

    }
    return no_star;
}


Your lines are displaying in reverse order from how you want them, right? So what you want to do is look at the code that prints the lines:

 for(rownum=0;rownum<=numrows;rownum++)
 {
  printchars(numrows-rownum, ' ');
  printchars((2*rownum-1), '*');
  printf("\n");
 }

and figure out how to make it run backwards. This code above calls printchars for rows with 2*rownum-1 stars up to 2*numrows-1 stars because rownum starts at 0 and counts up to numrows.

How could you change this so that you are making rownum start from numrows and count down to zero instead?


Try going through your code by hand, step by step.

Get some graph paper out.

Say your input is 5. Just going by what's in your listing (no execution) what does it say it will output to the screen? Draw it on the graph paper.

See if you can spot the error.

A couple of unsolicited suggestions:

  • Using numrows for your input and rownum for your index is confusing (and it's the source of your error). Consider making your index variable more distinct from your input (maybe rn).
  • Consider being consistent with your abbreviations. You use no_, No_of_, and num as an abbreviation for "number of."
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号