Multidimensional Arrays

The multidimensional arrays in C++ Construction and Examples. The multidimensional arrays are arrays within an array.

For example, an array with two rows and three columns

1   2   3
4   5   6

can be written as

#include
using namespace std;
int main()
{
   int myarray[2][3] = {{1, 2, 3},{4, 5, 6}};
   cout << myarray[0][0] << endl;
   cout << myarray[0][2] << endl;
   cout << myarray[1][2] << endl;
   cout << myarray[1][1] << endl;
   return 0;
}


Where int myarray[2][3] means array of size 2 rows and 3 columns. And,
myarray[0][0] means display element at row-1 and column-1.
myarray[0][2] means display element at row-1 and column-3.
myarray[1][2] means display element at row-2 and column-3.
myarray[1][1] means display element at row-2 and column-2.


All elements of the above multidimensional array (two rows and three columns) can be access using nested for loop. For example

#include
#include
using namespace std;
int main()
{
   int myarray[2][3] = {{1, 2, 3},{4, 5, 6}};
   for (int i=0; i<2; i++)
   {
     for (int j=0; j<3; j++)
     {
       cout << setw(4) << myarray[i][j];
     }
     cout << endl;   //to change line after each row
   }
}


Here we use setw(4) to include 4 spaces before each element to separate them. And to use setw() we have to include #include library.


Q.1 Write a program in C++ that takes marks in 4 subjects of 5 different students.

#include
using namespace std;
int main()
{
string students[5] = {"A", "B", "C", "D", "E"};
string subjects[4] = {"Math", "Finance", "C++", "Matlab"};
int marks;
for (int i =0; i<5; i++)
{
for (int j=0; j<4; j++)
{
cout << "Enter Marks of Student " << students[i] << ": " << endl;
cout << "Subject " << subjects[j] << ": ";
cin >> marks;
}
}
return 0;
}



Q.2 Write a program in C++ that takes marks in 4 subjects of 5 different students and display total marks obtained by each student.

#include
using namespace std;
int main()
{
string students[5] = {"A", "B", "C", "D", "E"};
string subjects[4] = {"Math", "Finance", "C++", "Matlab"};
int marks[4];
for (int i =0; i<5; i++)
{
int total_marks = 0;
for (int j=0; j<4; j++)
{
cout << "Enter Marks of Student " << students[i] << ": " << endl;
cout << "Subject " << subjects[j] << ": ";
cin >> marks[j];
total_marks = total_marks + marks[j];
}
cout << "Marks obtained by student " << students[i] << " are: " << total_marks << endl;
}
return 0;
}

RELATED PAGES
- Array
- Multidimensional Arrays


Basic Financial Terms
Basic Financial terms in Corporate and Mathematical Finance
Financial Portfolio Analysis
Selection of assets, risk and return, and portfolio analysis
Financial Mathematics Notes
View the online notes for Financial Mathematics (CT1)
Financial Computing with C++
Learn Financial Computing with C++ step by step