I want to be able to print a diamond like this when the user enters 5 for the diamond. But also will work for any value that is odd and greater than 0.
You are probably taking introductory C class right now, and as everyone else I would discourage you from copying, but for reference here is an answer:
To make the answer simple, all you need to know is how many spaces and stars to print.
The sequence is following: [print spaces] [print stars] [print spaces] [print '\n'].
Observe that in the middle row we would need: (0) spaces, (numStars) stars, (0) spaces.
In the row above and below, we would need: (1) space, (numStars - 2) stars, (1) space.
An so on...
This should give you the feeling that to count number of spaces, you need to count the distance from the middle row. Also note that with each row away from the middle, number of stars decreases by 2.
#include
#include
int main(int argc, char** argv) {
int num, middle, spaceCount, starCount;
printf("Enter a num:");
scanf("%d",&num);
middle = (num-1)/2;
for (int i = 0; i < num; i++){
spaceCount = abs(middle - i);
starCount = num - 2*abs(middle - i);
for(int c = 0; c < spaceCount; c++)
printf(" ");
for(int c = 0; c < starCount; c++)
printf("*");
for(int c = 0; c < spaceCount; c++)
printf(" ");
printf("\n");
}
return 0;
}
Since we are calculating the distance between the current row and the middle one, we need to know the absolute value. abs function is standard C function to do that.