1
votes

This program always provide me a different output, I'm confused how is this possible. Error is in the last loop which is under if conditional statement but don't know what is it?

#include <stdio.h>

int main()
{
    int n;
    printf("Enter the number upto which the pattern is to be printed \n ");
    scanf("%d", &n);

    /* Upside inverted V */

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

        for (int k = 1; k <= i; k++)
        {
            printf("%d", k);
        }

        if (i > 1)
        {
            for (int l = i - 1; l > 0; l--)
            {
                printf("%d", l);
            }
        }

        printf("\n");
    }

    // down V part

    for (int x = n - 1; x >= 1; x--)
    {
        for (int y = n; y > x; y--)
        {
            printf(" ");
        }

        for (int z = 1; z <= x; z++)
        {
            printf("%d", z);
        }

        if (x > 1)
        {
            for (int w = x - 1; w >= 1; w--)
            {
                printf("%d", &w);
            }
        }

        printf("\n");
    }

    return 0;
}

Removing the last loop get me run one third of my program or the pattern which I had wanted.

The incorrect output looks like this

2
What's the expected output? and the issue/error you have?Aziz
The compiler tells you what the problem is and which line the problem is on.Paul Hankin
Please post error messages into the question itself as text, not as an image that is hosted on an external service. There is nothing wrong with posting images in order to provide additional information, but all important information should be in the question itself as text. You may want to read this: Why not upload images of code/errors when asking a question?Andreas Wenzel

2 Answers

1
votes

If you enabled compiler warnings, the compiler would have shown you a warning in the line

printf("%d", &w);

You are printing the address of the variable instead of the variable value. Because w is a variable on the stack, that address can change if you rerun the program. Remove the & operator and it should print the correct value.

0
votes

In your last for loop there is printf("%d", &w);. The &w is incorrect, you have to use printf("%d", w); instead. It prints every time a different value beacause you are printing not the value in w, but where the value is stored.

I think you can improve your code with functions like the following and use them instead of repeating the same type of for.

void printNTimesChar(int n, char c){
  for(int i=0;i<n;i++){
    printf("%c", c);
  } 
} 
void printNTimesInt(int n, int value){
   for(int i=0;i<n;i++){
     printf("%d", value);
   }
}