/**Solution to exercise 5.8, p. 199, "C by Dissection"
*
*
* Prints a diamond in the middle of the screen. The diamond is printed by printing two halves, upper
* and lower.
*
* 07. March, Lone Leth Thomsen
**/
#include <ctype.h>
#include <stdio.h>
#define N 5
void repeat (char c, int how_many) /* prints a character on the screen how_many times */
{
int i;
for (i=0; i < how_many; ++i)
putchar(c);
}
int main(void) /* main program */
{
char c = 'X'; /* the character X will be printed */
int i;
/* upper half of diamond */
for (i = 1; i < N; i += 1){
repeat(' ',(N-i)); /* prints blanks N-i times */
repeat(c,i); /* then prints X i times */
repeat(c,i); /* then prints X i times again */
putchar('\n'); /* finally newline. Could also have been done by printing blanks again */
};
/* lower half of diamond */
for (i = 1; i < N; i += 1){
repeat(' ',i); /* prints blanks i times */
repeat(c,(N-i)); /* then prints X N-i times */
repeat(c,(N-i)); /* then prints X N-i times again */
putchar('\n'); /* finally newline. */
}
return 0;
}
![]() | #define N 5 |
defines width |
![]() | void repeat (char c, int how_many) /* prints a character on the screen how_many times */ |
prints a character on the screen how_many times |
![]() | char c = 'X'; /* the character X will be printed */ |
the character X will be printed |
![]() | for (i = 1; i < N; i += 1){
repeat(' ',(N-i)); /* prints blanks N-i times */
repeat(c,i); /* then prints X i times */
repeat(c,i); /* then prints X i times again */
putchar('\n'); /* finally newline. Could also have been done by printing blanks again */
};
|
upper half of diamond |
![]() | for (i = 1; i < N; i += 1){
repeat(' ',i); /* prints blanks i times */
repeat(c,(N-i)); /* then prints X N-i times */
repeat(c,(N-i)); /* then prints X N-i times again */
putchar('\n'); /* finally newline. */
}
|
lower half of diamond |