0
#include<iostream>
#include<conio.h>
using namespace std;
const int maxRows =3;
const int maxCols =3;
//prototype declaration
 void readMatrix(int[][maxCols]);
void displayMatrix(int[][maxCols]);
//void displayFlippedMatrix(int [][maxCols]);
//
 main(){
    int a[maxRows][maxCols];
    //read the matrix elements in array
    readMatrix(a);
     //display the original matrix
     cout<<"\n\n"<<"the original matrix is: "<<'\n';
    displayMatrix(a);
    //display the flipped matrix
    cout<<"\n\n"<<"the flipped matrix is :"<<'\n';
//      displayFlippedMatrix(a);




    getch();
    system("pause");
}

void readMatrix(int a[][maxCols]){
    int row,col;
    for(row=0; row<maxRows; row++){

        for(col=0; col<maxCols; col++){

            cout<<"\n"<<"Enter"<<row<<","<<col<<"Element:";
            cin>>a[row][col];
        }
        cout<<'\n';
    } 
 }
// end of read Matrix........
void displayMatrix(int a[][maxCols]){
    int row,col;
    for(row=0; row<maxRows; row++){

        for(col=0; col<maxCols; col++){
            **cout<<a[0][1]<<'\t';**
        }
        cout<<'\n';
    }
 }

// end of displayMatrix......

/*
 void displayFlippedMatrix(int a[][maxCols]){
    int row,col;
     for(row=maxRows-1; row>0; row--){

         for(col=0; col<maxCols; col++){
             cout<<a[row][col]<<'\t';
         }
         cout<<'\n';
     }
 }*/

here i have complete code of flipping matrix from last row in to first row and first row in to last row and this code is working perfectly but i have one question and i want to understand it if any one i just want to print a matrix i.e cout<<<'\t';in a single row and only second column as i know that [0][1] zero for known as first row and [1] is known as second column but it is actually printing all rows and all columns even though i have only cout[0][1] first row and second column.

Raheel Almis
  • 73
  • 3
  • 8

2 Answers2

1

You're only print out a[0][1], but you do it multiple times. You print the same value maxRows * maxCols times because you have it inside a nested loop.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

In the displayMatrix(), your loops control how many times the cout command executes. So you are basically printing a[0][1] maxcols times in a row for every maxrows rows. If your original matrix is something like this:

           1 2 3
a[3][3] =  4 5 6
           7 8 9

Your output will be something like this:

2 2 2
2 2 2
2 2 2

To fix this, make these changes to the code:

void displayMatrix(int a[][maxCols]){
    int row,col;
    cout<<"First row:\n";
    for(col=0; col<maxCols; col++){
         cout<<a[0][col]<<'\t';
    }
    cout<<"\n\nSecond column:\n";
    for(row=0; row<maxRows; row++){
         cout<<a[row][1]<<'\n';
    }
}

And the output will look something like this:

First row:
1 2 3

Second Column:
2
5
8
Sahil Arora
  • 875
  • 2
  • 8
  • 27