'How to go to next line after every row in a 2D array?
So I need to come up with something like this: It's a layout of seats on an airplane.
1 A B C D
2 A B C D
3 A B C D
4 A B C D
5 A B C D
6 A B C D
7 A B C D
But instead my code prints this:
ABCD
ABCABCD
ABCABCD
ABCABCD
ABC
This is my code, any help would be really appreciated. I just started working with arrays
#include <iostream>
using namespace std;
int main ()
{
char airplane[7][4] = {{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'}};
for (int i=0; i<4; i++)
{
for (int j=0; j<7; j++)
{
cout<<airplane[i][j];
if (airplane[i][j]=='D')
{
cout<<endl;
}
}
}
system ("PAUSE");
return 0;
}
Solution 1:[1]
Here the code :
#include <iostream>
using namespace std;
int main ()
{
char airplane[7][4] = {{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'}};
for (int i=0; i<7; i++)
{
cout << i+1;
for (int j=0; j<4; j++)
{
cout<<airplane[i][j];
if (airplane[i][j]=='D')
{
cout<<endl;
}
}
}
system ("PAUSE");
return 0;
}
Solution 2:[2]
Change the for loop in this fashion
for (int i=0; i<7; i++)
{
cout<<i+1;
for (int j=0; j<4; j++)
{
cout<<' ';
cout<<airplane[i][j];
}
cout<<endl;
}
Solution 3:[3]
Try running your outer loop for 7 times and inner loop for 4 times. Include cout<
And by the way the code given by Bui Akinori is buggy for if you change the number of seats in each row to five.
Solution 4:[4]
try this..:-->
#include <iostream>
using namespace std;
int main ()
{
char airplane[7][4] = {{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'},
{'A', 'B', 'C', 'D'}};
for (int i=0; i<7; i++) //Row
{
cout<<i+1;
for (int j=0; j<4; j++) //Column
{
cout<<airplane[i][j];
cout<<" ";
}
cout<<endl;
}
system ("PAUSE");
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ??c Bùi |
Solution 2 | kjana83 |
Solution 3 | 10101010 |
Solution 4 |