Reputation: 27
for(int width=1; width<=5; width++) {
if(width <= 1) {
for(int width=1; width<=5; width++) {
cout<<" "<<width<<" ";
}
} else if(width<5) {
cout<< endl;
for(int width2=5; width2<=9; width2++) {
if(width2==5 || width2==9)
cout<<" "<<width2<<" ";
else
cout<< " ";
}
} else {
cout<< endl;
for(int width3=13; width3>=9; width3--) {
cout<<" "<<width3<<" ";
}
}
}
this code which I have posted above draws this shape
1 2 3 4 5
5 9
5 9
5 9
13 12 11 10 9
but I actually want my code to print it like this, I have tried a lot changing things but all in vain. so, I'm looking forward to you guys.
1 2 3 4 5
16 6
15 7
14 8
13 12 11 10 9
Upvotes: 1
Views: 179
Reputation: 37
Here is solution
int width =6;
int total = (width-1)*4;
for(int row=1; row <=width; row++)
{
if(row == 1 )
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<pr<<" ";
}
cout<<"\n";
}
else if( row == width)
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<(total-row-pr+3)<<" ";
}
}
else
{
for(int pr=1; pr<=width; pr++)
{
if(pr ==1 )
cout<<" "<<(total-row+2)<<" ";
else if(pr ==width)
cout<<" "<<(width+row-1)<<" ";
else
cout<<" "<<" "<<" ";
}
cout<<"\n";
}
}
Upvotes: 1
Reputation: 1427
It helps to avoid magic numbers in your code using #defines
or const
variables. This makes it more readable and more extensible. For example if you wanted to make a square that was 20x20, your code would require a complete rewrite!
Start from this working solution to implement this principle into your coding.
#include <iostream>
using namespace std;
#define SIDE 4
int main(){
int perimeter = SIDE * 4;
for(int width=0; width<=SIDE; width++)
{
if(width < 1) {
for(int width=0; width <= SIDE; width++) {
cout<<" "<<width + 1<<" ";
}
cout<< endl;
}
else if(width < SIDE)
{
cout<<" "<<perimeter - width + 1 << "\t\t" << (SIDE + width) + 1;
cout<< endl;
}
else
{
for(int width3 = perimeter - SIDE; width3 >= perimeter - 2 * SIDE; width3--) {
cout<<" "<<width3 + 1<<" ";
}
cout<< endl;
}
}
return 0;
}
Upvotes: 1
Reputation: 2537
If you print something on the console, going back in lines and carriage returns will be very messy.
The trick is to seperate the problem in 3 stages:
stage1: print the top line, simple enough
stage2: print the largest number wrapping around, then print some empty space and finish with the number at the end, make sure to increment and decrement the numbers accordingly.
stage3: print the last line.
Here is the code for the algorithm I just described:
#include <iostream>
using namespace std;
int main()
{
const int width=6;
const int height=6;
int numberInFront=(height-1)*2 + (width-1)*2;
int numberAtTheEnd= width;
for(int i=1; i<width; ++i) cout<<i<<"\t"; //print top line
cout<<endl;
for(int i=0; i<height-1; ++i)
{
cout<<numberInFront<<"\t";
for(int j=0; j<width-3; j++) cout<<"\t"; //print inner space
cout<<numberAtTheEnd<<endl;
numberInFront--;
numberAtTheEnd++;
}
//print last line:
int counter = numberInFront;
while(counter!=numberAtTheEnd-1)
{
cout<<counter<<"\t";
counter--;
}
return 0;
}
Upvotes: 1