## Student Marks 3 Subjects 2D Array

Showing how multiple students marks in multiple subjects can be stored and used in 2D Array.

## Learning Objectives

- Declaration and initilisation of integer 2D Arrays.
- Traversing 2D array with nested loops.
- Picking Data from 2D array.
- Making calculations on data picked from 2D array.
- Learning to set precision of fractions.

## Program Approach

Some fixed data will be initialised in the 2D array with correctly set choice of rows and columns. Rows shall be traversed with the outer loop and columns in each row shall be traversed with inner loop. Data shall be picked from each location using arrayname[row_position][column_position] form of variable. Calculation of each data item will normally be done as per need and positioned accordingly in the inner loop and outer loop.

## Source Code

## Run Output

## Code Understanding

**int M[2][3]={{47,75,80},{52,81,76}}; **

Here 2D array has been initialised where first figure [2] is number of rows, which represents number of students in this case and second figure [3] is number of columns, which represents subject marks. Initialisation is also nested with each member representing a row and the nested member as column. This is also called row based linearization.

**for ( int i = 0; i < 2; i++ ) {**

This is outer loop for two rows.

** p=0;**

This is reinitialised everytime in the beginning as the last value read has no significance in the next operation.

**for ( int j = 0; j < 3; j++ ) {**

This is inner loop to traverse each column of a given row.

**p+=M[i][j];**

Each member of the row has been summed within the inner loop so that sum of subject marks can be obtained. With **M[i][j]** corresponding marks for each subject is read. i for row position and j for column position within each row.

**float pm=(float) p/3;**

Here average is being taken by dividing the sum with number of subjects as fixed value of 3. The numerator will be typecasted to float as final value of average can be a float value. If we do not typecast the decimal portion of calculation will be lost.

**cout<<setprecision(2)<<fixed; **

This line allows to print the final output with upto two places of decimal. **setprecision(2)** needs **iomanip** include file. The **fixed** type allows to print as normal form of decimal fraction and not the scientific notation form.

cout<<“% Marks Student”<<i+1<<” = “<<pm<<endl;

Here i+1 has been given as the i index starts with 0 and we want to print student 1, student 2 etc. successively. **pm** will contain the percentage marks as calculated in the previous line.

## Notes

One can also try to calculate size of array using sizeof operator for loop count calculations.

**Suggested Filename(s): **marks.cpp, marks2d.cpp, manysubjectsmarks.cpp

sunmitra| Created: 4-Dec-2017 | Updated: 8-Dec-2017|