Feb 27, 2016 at 10:17am UTC
Hi there,
Just started learning C++ and would like to ask here how do i start when 2d array is used to convey this information
int stalls[3][6] = {{1,0,0,0,1,1},
{1,1,1,1,1,1},
{0,0,0,1,1,1,};
if i want my output to be like this as shown below:
Mon Tues Wed Thurs Fri Sat
Stall 1 open close close close open open
Stall 2 open open open open open open
Stall 3 close close close open open open
Appreciate if you all can help.
Thanks
Feb 27, 2016 at 10:21am UTC
First print the heading rows.
Then repeat 3 times, print the prefix "Stall" and row number
repeat 6 times print open/close depending on array value.
Last edited on Feb 27, 2016 at 10:22am UTC
Feb 27, 2016 at 10:24am UTC
This is what i have done:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const char stalls = 3; const char days = 6;
void display(int[stalls][days]); // function prototype
int main()
{
char stalls[3][6] = {{1,0,0,0,1,1},
{1,1,1,1,1,1 },
{0,0,0,1,1,1} };
display(stalls);
return 0;
}
void display(char nums[stalls][days])
{
char rowNum, colNum;
for (rowNum = 0; rowNum < stalls; rowNum++)
{
for (colNum = 0; colNum < days; colNum++)
cout << setw(4) << nums[rowNum][colNum];
cout << endl;
}
cin.ignore();
return;
}
Feb 27, 2016 at 10:32am UTC
The code doesn't compile for me. You need to change char
to int
almost everywhere throughout the program.
*Technically a char is a type of integer having a range of 256 possible values, but it is confusing to both the reader and the compiler here.
Now you just need to add the row/column headings and print the word open/close instead of digit 1/0.
Last edited on Feb 27, 2016 at 10:36am UTC
Feb 27, 2016 at 10:37am UTC
Thanks Chervil.
The program works after i change char to int. however how to i display additional information like stall 1 on row and Mon on column.
Also converting 1 to open while 0 to close
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int stalls = 3; const int days = 6;
void display(int[stalls][days]); // function prototype
int main()
{
int stalls[3][6] = { { 1,0,0,0,1,1 },
{ 1,1,1,1,1,1 },
{ 0,0,0,1,1,1 } };
display(stalls);
return 0;
}
void display(int nums[stalls][days])
{
int rowNum, colNum;
for (rowNum = 0; rowNum < stalls; rowNum++)
{
for (colNum = 0; colNum < days; colNum++)
cout << setw(4) << nums[rowNum][colNum];
cout << endl;
}
cin.ignore();
return;
}
Feb 27, 2016 at 10:48am UTC
The heading text is straightforward.
open/close - you could use an if
statement or maybe add a simple 1d array of character strings containing those words and use 0/1 as the subscript.
Or a variation on the if statement, the conditional or ternary operator ?
.