I written a pattern printing code for odd number of lines of the famous hollow diamond (stars + spaces + stars) code in cpp as follows :-
#include <iostream>
using namespace std;
int main(){
int tr;
cin >> tr;
//first row
int firststar = 1;
while (firststar <= tr){
cout << "*";
firststar++;
}
cout << endl;
int firsthalf = 1;
while (firsthalf <= (tr-1/2)) {
//stars
int star1 = 1;
while (star1 <= (((tr-1/2)+1)/2-firsthalf) ){
cout << "*" ;
star1++;
}
//spaces
int spaces1 = 1;
while (spaces1 <= 2 * firsthalf - 1){
cout <<" ";
spaces1++;
}
//stars
star1 = 1;
while (star1 <= (((tr-1/2)+1)/2-firsthalf) ){
cout << "*" ;
star1++;
}
firsthalf++;
cout << endl;
}
int secondhalf = 1;
while (secondhalf <= ((tr-1) /2)-1){
//stars
int star2 = 1;
while (star2 <= secondhalf+1){
cout << "*" ;
star2++;
}
//spaces
int spaces2 = 1;
while (spaces2 <= 2 * ((tr - 1) / 2 - secondhalf) - 1){
cout << " ";
spaces2++;
}
//stars
star2 = 1;
while (star2 <= secondhalf+1){
cout << "*" ;
star2++;
}
cout<< endl;
secondhalf++;
}
//last row
int laststar = 1;
while (laststar <= tr){
cout << "*";
laststar++;
}
return 0;}
I tried running the code after dry testing the code (checking the logic of the stars and spaces) several times, but it still prints extra spaces/ lines after the first half
>Solution :
Honestly your code would be much shorter and less bug-prone, if you would just reuse the code as functions. For example:
#include <iostream>
using namespace std;
void draw(char symbol, size_t count) {
while (count--){
cout << symbol;
}
}
void drawRow(size_t numStars, size_t size) {
draw('*', numStars);
draw(' ', size - 2*numStars);
draw('*', numStars);
cout << endl;
}
int main()
{
int size = 7;
int radius = size / 2;
// first row
draw('*', size);
cout << endl;
// upper half
for (int numStars = radius; numStars > 0; --numStars) {
drawRow(numStars, size);
}
// lower half
for (int numStars = 2; numStars <= radius; ++numStars) {
drawRow(numStars, size);
}
// last row
draw('*', size);
}
This would draw you:
*******
*** ***
** **
* *
** **
*** ***
*******
You just need adjust this code to provide size of your drawing from console input
EDIT – Version without defining functions
#include <iostream>
using namespace std;
int main()
{
int size = 7;
int radius = size / 2;
// first row
{
int numSymbols = size;
while (numSymbols--) {
cout << '*';
}
}
cout << endl;
int numStars = size / 2 + 1;
for (int row = 1; row < size-1; ++row) {
// while first half (rows 1, 2, 3, ... size/2) decrease number of stars
// while second half (rows size/2+1, size/2+2, ..., size-1)
if (row <= size / 2) {
--numStars;
} else {
++numStars;
}
if (numStars < 0) {
numStars = -numStars;
}
{
int numSymbols = numStars;
while (numSymbols--) {
cout << '*';
}
}
{
int numSymbols = size - 2*numStars;
while (numSymbols--) {
cout << ' ';
}
}
{
int numSymbols = numStars;
while (numSymbols--) {
cout << '*';
}
}
cout << endl;
}
// last row
{
int numSymbols = size;
while (numSymbols--) {
cout << '*';
}
}
cout << endl;
}
