Printing a Diamond Pattern in C
In this tutorial we are looking at how to print a diamond pattern using the C language. The diamond pattern algorithm question is often used in C courses, so it make sense that we also take a look at it.
Take a look at the diamond pattern C source code:
#include <stdio.h>
int main() {
int rows, a, b, space = 1;
printf("Enter number of rows:");
scanf("%d", &rows);
//Or use scanf_s to prevent buffer overloading
//scanf_s("%d", &rows, 1);
// Print first half of the triangle.
space = rows - 1;
for ( b = 1 ; b <= rows ; b++ ) {
for ( a = 1 ; a <= space ; a++ )
printf(" ");
space--;
for ( a = 1 ; a <= 2*b-1 ; a++)
printf("*");
printf("\n");
}
// Print second half of the triangle.
space = 1;
for ( b = 1 ; b <= rows - 1 ; b++ ) {
for ( a = 1 ; a <= space; a++)
printf(" ");
space++;
for ( a = 1 ; a <= 2*(rows-b)-1 ; a++ )
printf("*");
printf("\n");
}
return 0;
}
First we ask for the number of rows we want the diamond half’s to be. (As you can see we use scanf, but we put the scanf_s example (scanf on windows is deprecated) for your convenience). Then we print the top half of the diamond pattern, we are using three for loops for that. The first for loop keeps track of the number of rows. The second for loop is to set the spaces before the stars (that are set by the third for loop.
The second set of three for loops are used to print the second part of the diamond pattern. We end by returning zero.
That’s all, as you can see it is a diamond pattern program is easy to make. Play with the for loop settings to see what each loop does. Good luck!
Really sir,,,,, u r awesome !!!!!!
thank you sir this is really help sir
I put in 36. it was a neat surprise. thanks.