I've to create a sort-of Christmas greeting card which needs to include designs generated using nested-for loops.
The output needs to have a border on all four sides with variable text inside along with the nested-for loop designs.
Something along the lines of this:
I tried using a for-loop to generate the border a put the designs inside, but the problem arose when printing multiline designs.
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
char tree[10][10];
int i,j;
for(i=0; i<7; i++){
for(j=0; j<7; j++){
if(i==0 && j==3){
// cout << '*';
tree[i][j] = '*';
}
else if(i==1 && j==3){
// cout << '|';
tree[i][j] = '|';
}
else if(i==2 && j==3){
// cout << 'M';
tree[i][j] = 'M';
}
else if(i==3 && j>1 && j<5){
// cout << 'A';
tree[i][j] = 'A';
}
else if(i==4 && j>0 && j<6){
if(j % 2 == 0){
// cout << 'o';
tree[i][j] = 'o';
} else {
// cout << 'A';
tree[i][j] = 'A';
}
}
else if(i==5){
if(j % 2 == 0){
// cout << 'A';
tree[i][j] = 'A';
} else {
// cout << '~';
tree[i][j] = '~';
}
}
else if(i==6 && j==3){
// cout << "M";
tree[i][j] = 'M';
}
else {
// cout << ' ';
tree[i][j] = ' ';
}
}
tree[i][7] = '\n';
}
tree[6][8] = '\0';
for(i=0; i<30; i++){
for(j=0; j<70; j++){
if(i==0 || i==29){
cout << "^";
} else if(j==0 || j==69){
cout << "*";
}
int a,b;
if(j>=42 && j<50 && i >= 10 && i< 17){
for(a=0; a<7; a++){
for(b=0; b<8; b++){
cout << tree[a][b];
j++;
}
i++;
}
}
else {
cout << " ";
}
}
cout << endl;
}
return 0;
}
This pushes the entire border down, since the design is multiline.
I'm a little stumped about the approach. Perhaps using setw()
?
So I figured a solution to my question.
Instead of printing directly to stdout, I'm storing the output in a 2D char array.
The following will store the border:
for(i=0; i<50; i++){
for(j=0; j<70; j++){
if(i==0 || j==0 || i==49 || j==69){
finalOutput[i][j] = '*'; //Just for the sake of an example
} else {
finalOutput[i][j] = ' ';
}
}
}
And the following will store the tree at some place inside the box,
for(i=30; i<7; i++){
for(j=30; j<7; j++){
finalOutput[i][j] = tree[i-30][j-30];
}
}
Then printing finalOutput solves my problem.