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.
I don't want to give you the code, you should learn.
The input number will be the width of the diamond, so make sure to make a relation between the spaces and asterisks that does not surpass this number.
The main idea would be to start at 1 asterisk, and increment by two each time until the input number is reached.
Also, do something to prevent an error if the user enters an even number.
static void Main(string[] args)
{ //check this out more optimized code hope it will be help full.
for (int row=-2;row<=2;row++)
{
for (int col=-2;col<=2;col++)
{
if (Math.Abs(row)+Math.Abs(col)<=2)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
Console.ReadKey();
}
There are two things that occur here:
Indent changes (-1 to "mid", +1 "after")
Star count changes (+2 to "mid", -2 "after")
Now, this could be done with two loops (one for the top to "mid" and one "after"), but the values can also be determined with a little math. Let's explore that :-)
Here are the numbers:
s(spaces) x(stars) n(line number) __X 2 1 0 _XXX 1 3 1 XXXXXX 0 5 2 _XXX 1 3 3 __X 2 1 4
Start by noting that s
is symmetrical about the "mid":
And then that x
is related to s
(by 2 as noted in deltas above):
Hope that gives some insight!
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 <stdio.h>
#include <stdlib.h>
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.