Printing "Diamond " with full commenting

10:06 0 Comments A+ a-

Problem:
                       Print Diamond on Console
Solution:
# include <iostream>
using namespace std;
int main()
{
int s, p, n; //s is used for spacing, p is used for printing *, n is taken as integer for size of diamond
cout << "Enter the size of Diamond (must be odd and >=5) : " ;
cin >> n;

while (n % 2 == 0 || n<5)
{
cout << "The size n should be odd number (& >=5)" << endl;
cout << "Enter the size of Diamond again (must be odd and >=5) : ";
cin >> n;
}
s = n / 2; //s is taken n/2 as space for the first line starric is n/2
p = 1; // p is taken 1 as only 1 * is to be printed in 1st line

for (int i = 0; i<n / 2 + 1; i++) //loop for the upper half of diamond including middle line
{
for (int a = 0; a<s; a++) //loop for spacing in upper half
{
cout << " ";
}
s--; //1 is subtracted from s each time to reduce spacing on left side of pattern by 1
for (int b = 0; b<p; b++) //loop for printing *
{
cout << "*";
}
p += 2; //2 is added to p each time as in upper half the * are to increase 2 by each time until n
cout << endl;
}
s = 1; //s is again initalized 1 as only one space appear in the line below the central line 
p = n - 2; //2 is deducted from p each time to reduce the number of starric by 2 each time until 1
for (int j = 0; j<n / 2; j++) // loop for lower half of diamond excluding the central line
{
for (int c = 0; c<s; c++) //loop for spacing in the lower half
{
cout << " ";
}
s++; //1 is added to spacing each time as the space increases each time by 1 on left side in the lower half
for (int d = 0; d<p; d++) //loop for printing *
{
cout << "*";
}
cout << endl;
p = p - 2; //2 is subtracted from p each time to reduce number of starric * each time by 2
}


system("pause");
return 0;
}