Using simple mathematics and a little knowledge of nested for loops and if else conditionals, we can construct a hollow diamond without using a graphics library.
First, our program prints four quadrants in form of a grid using nested for loop. In the next step, an if conditional restricts the grid in form of a hollow diamond and prints building characters in that shape.
#include <stdio.h> int main() { // Author : Faizan int a,h,m,e,d,f,z,n; printf("\t\t * * * * * \n\t PROGRAM TO PRINT A DIAMOND \n\t\t * * * * * \n"); printf("\n Please Enter # Of Rows (Height) : "); scanf("%d",&a); // User decides the rows (height) of the diamond if (a%2 == 0) a +=1; /* To preserve the symmetry, if height is an even number; it is replaced by an odd number */ h=(a-1)/2; for (e=h; e>=-h; e--) { printf("\n"); for (d=-h; d<=h; d++){ f = h*h; z = d*d + e*e - 2*e*d; // (a-b)^2 n = d*d + e*e + 2*e*d; // (a+b)^2 if (z == f || n == f) // restricting the grid to a hollow diamond printf("#"); else printf(" "); } } system("pause"); }
No comments:
Post a Comment