Print a "Diamond "
Problem:
Print Diamond on Console
Solution:
# include <iostream>using namespace std;
int main()
{
int size, space, star; //space for spacing, star for printing *, size for size of diamond
cout << "Enter the size of Diamond (must be odd and >=5) : " ;
cin >> size;
while (size % 2 == 0 || size<5)
{
cout << "Invalid Input" << endl;
cout << "Please Enter again (must be odd and >=5) : ";
cin >> size;
}
space = size / 2; //As space for the first line is size/2
star = 1; //Star is taken 1 as only 1 * is to be printed in 1st line
for (int i = 0; i<size / 2 + 1; i++) //loop for the upper half including middle line
{
for (int a = 0; a < space; a++) //loop for spacing in upper half
{
cout << " ";
}
for (int b = 0; b < star; b++) //loop for printing *
{
cout << "*";
}
star += 2; //As in upper half two * are increased
space --; //As to reduce spacing on left side of pattern by 1
cout << endl;
}
space = 1; //As only one space appear in the line below the central line
star = size - 2; //As to reduce the number of starric by 2 each time until 1
for (int j = 0; j < size / 2; j++) // loop for lower half of diamond
{
for (int c = 0; c < space; c++) //loop for spacing in the lower half
{
cout << " ";
}
space++; //As the space increases each time by 1 on left side in the lower half
cout << endl;
}
space = 1; //As only one space appear in the line below the central line
star = size - 2; //As to reduce the number of starric by 2 each time until 1
for (int j = 0; j < size / 2; j++) // loop for lower half of diamond
{
for (int c = 0; c < space; c++) //loop for spacing in the lower half
{
cout << " ";
}
space++; //As the space increases each time by 1 on left side in the lower half
for (int d = 0; d < star; d++) //loop for printing *
{
cout << "*";
}
cout << endl;
star -= 2; //As to reduce number of starric * each time by 2
}
system("pause");
return 0;
}
{
cout << "*";
}
cout << endl;
star -= 2; //As to reduce number of starric * each time by 2
}
system("pause");
return 0;
}

No comments:
Post a Comment