In: Computer Science
Please, use C++ for this question.
(b) Write the definition of displayBox() function. The function will display a matrix of integers from 1 to 4 such that the first row will contain four 1s, the second row will contain four 2s, the third row will contain four 3s and the fourth row will contain four 4s. Function must use nested loops to display each column and row heading as well as the numbers. The function has no parameters and no return value.
The output should look something like this:
1 2 3
4
-------------------------
1 | 1 1 1 1
2 | 2 2 2 2
3 | 3 3 3 3
4 | 4 4 4 4
Use standard C++ stream I/O for output and manipulators for formatting. No main() or #includes are required.
complete program with driver code :
#include<iostream>
#include<iomanip>
using namespace std;
void displayBox()
{
int width = 5;
/* setw(n) sets the output width to n including the space taken care by character after setw*/
cout <<" "<< setw(width) << "1" << setw(width) << "2" << setw(width) << "3" << setw(width) << "4"; // print header line
cout<<endl;
for (int i = 1; i <= (width * 5 + 2); i++) /* loop to print '-'. no of '-' is equal to 2 + number of characters in header * width */
{
cout << "-";
}
cout << endl;
for (int i = 1; i <= 4; i++) /* loop to print rest of the matrix */
{
cout << i << "|";
for (int j = 1; j <= 4; j++)
{
cout << setw(width) << j;
}
cout << endl;
}
}
int main()
{
displayBox();
return 0;
}
displayBox function :
void displayBox()
{
int width = 5;
/* setw(n) sets the output width to n including the space taken care by character after setw*/
cout <<" "<< setw(width) << "1" << setw(width) << "2" << setw(width) << "3" << setw(width) << "4"; // print header line
cout<<endl;
for (int i = 1; i <= (width * 5 + 2); i++) /* loop to print '-'. no of '-' is equal to 2 + number of characters in header * width */
{
cout << "-";
}
cout << endl;
for (int i = 1; i <= 4; i++) /* loop to print rest of the matrix */
{
cout << i << "|";
for (int j = 1; j <= 4; j++)
{
cout << setw(width) << j;
}
cout << endl;
}
}
output screen shot