As a student, you may need to stupid things in order to get good grades. Although you may never need to draw a diamond shape somewhere in your job with code, you will need to do this when you study about programming.
In this article, we'll share with you a very simple script to create a diamond shape output according to X rows in the console with the C programming language:
#include <stdio.h>
int main()
{
int n, c, k, space = 1;
printf("Enter number of rows: \n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++){
printf(" ");
}
space--;
for (c = 1; c <= 2*k-1; c++){
printf("*");
}
printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++){
printf(" ");
}
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++){
printf("*");
}
printf("\n");
}
return 0;
}
The program will prompt for the number of rows that the diamond should have and will print it in the console.
Print diamond with custom character
If instead a single asterisk, you want to use a custom character you can prompt the user for the character. Follow the same logic, but create an extra variable of the char type that will be updated by the requested value:
#include <stdio.h>
int main()
{
int n, c, k, space = 1;
char Ch;
printf("Please Enter any Symbol\n");
scanf("%c", &Ch);
printf("Enter number of rows: \n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++){
printf(" ");
}
space--;
for (c = 1; c <= 2*k-1; c++){
printf("%c", Ch);
}
printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++){
printf(" ");
}
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++){
printf("%c", Ch);
}
printf("\n");
}
return 0;
}
This program will prompt for 2 values, the number of rows of the diamond and the character that will be used to draw it:
Happy coding !