0

I can't figure out the problem in my code, it successfully creates a pyramid but doesn't reprompt when value other than 1-8 is entered, also it gives a space before printing the pyramid, causing errors in check50. Please correct this code. The output I get with Check 50 is like:

handles a height of 2 correctly
expected "" #  #"\n"##  ...", not ""  #  #"\n" ##..."
are you printing an additional character at the beginning of each line?

and here is the code:

   #include<stdio.h>
#include<cs50.h>
int main(void)
{
    int n;
    input:
 n = get_int("Enter a number=\n");
 if(n>=1&&n<=8)
 {
  for(int i=1;i<=n;i++)                             //FOR THE RIGHT LEANING TRIANGLE
  {
     for(int k=n-i;k>=0;k--)
     {
       printf(" ");
     }
     for(int j=1;j<=i;j++)
     {
         printf("#");
     }
     printf("  ");                                       //FOR THE 2 SPACES
     for(int b=1;b<=i;b++)                              //FOR THE LEFT LEANING TRIANGLE
        {
            printf("#");
        }
        printf("\n");
   }

 }
 else
{
    goto input;
}
 }
1

EEK: The dreaded goto statement!!

It's almost always a bad practice to use a goto statement and should be avoided whenever possible!!!!

The next bad practice is encapsulating the bulk of a program in an if or else condition.

When checking or validating input like this, one should always do that and only that in a localized code block.

In this case, you should consider coding to pseudocode that looks something like this:

get input
validate input
if it's bad do it again.

otherwise continue to process the input.

You might try something like this:

do
{
   // code to get input goes here
} 
while( test for BAD data to restart loop);
//continue coding from here

This has the beauty of looping until you get the desired input and not entangling or coupling to the code that follows. It will be completely independent.

I could tell you how to fix the original code, but I don't want to teach you any bad practices.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |
  • Yes I know that I shouldn't have used the goto statement but what about the working of code, my code can make pyramid but what should I do about the space with the edge of output screen? – Apoorv Saxena Jul 4 at 8:27
  • that's easy. print one less leading space. Adjust the values in the for loop to do this. – Cliff B Jul 4 at 21:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .