'Diamond pattern in C programming encountered an error in last loop, this program always provide me a different output, how is this possible anyhow? [closed]
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.
Solution 1:[1]
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.
Solution 2:[2]
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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jakob Stark |
| Solution 2 | Cucchi |

