LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   2d array (https://www.linuxquestions.org/questions/linux-newbie-8/2d-array-939404/)

kakalig2007 04-12-2012 02:57 AM

2d array
 
I know that this is silly but I cannot find anything on the web on how to read numbers from keyboard for a 2d array in bash shell script and to display it.

pan64 04-12-2012 03:30 AM

which language, how do you want to display (gui maybe?). Can you please give more details

Satyaveer Arya 04-12-2012 02:56 PM

This is the C++ code you can check:

Code:

#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <conio.h>
using namespace std;

const int ROWS = 2;
const int COLUMNS = 3;

int main() {
  ifstream inFile;
  int myArray[ROWS][COLUMNS]; 
  int r;
  int c;

  inFile.open("test.txt");
  if (!inFile) {
    cout << "Unable to open file";
    exit(1);
  }

  for(r=0; r<ROWS; r++) {
    for(c=0; c<COLUMNS; c++) {
      inFile >> myArray[r][c];
    }
  }

    for(r=0; r<ROWS; r++) {
    for(c=0; c<COLUMNS; c++) {
      cout << myArray[r][c] << " ";
    }
    cout << endl;
  }
  inFile.close();
  return 0;
}

Hope it will help you.

David the H. 04-13-2012 11:50 AM

bash only has simple one-dimensional arrays. You have to use a more advanced language, like awk or perl, to get into higher dimensions.

Check out the array section of the gawk manpage, for example.
http://www.gnu.org/software/gawk/man...de/Arrays.html


(Edit: And see here for arrays in bash: http://mywiki.wooledge.org/BashFAQ/005)


How about explaining in detail exactly what you want to do, and give a real example of the input you have and the output you want?

kakalig2007 04-16-2012 02:48 AM

I would like input as in c/c++:
for (i=0;i<n1;i++)
for (j=0;j<n2;j++)
read a[i][j] /*a[i][j] is the array name */

/* do some processing*/

and for output:
for (i=0;i<n1;i++)
for (j=0;j<n2;j++)
write a[i][j]

pan64 04-16-2012 03:38 AM

there is no 2d array in bash, so you need to simulate it somehow. if you need only numbers (as you wrote in your first post) you can have a chance, but in general there will be no solution. Also bash is limited in size, it will not be able to handle huge arrays.

So first you need to read dimensions, it is something like this:
Code:

echo -n enter n1:
read n1
echo -n enter n2:
read n2

you need some check on these inputs, but in this simple case we will skip this step.
you can organize for loops based on these examples: http://www.cyberciti.biz/faq/bash-for-loop/
Code:

for (( i=1; i<=$n1; i++ ))
do
  for (( j=1; j<=$n2; j++ ))
  do
    echo -n enter element'['$i']['$j']':
    read a
    array[$i]+=" $a"
  done
done

finally you can print this 'pseudo-2d' array:
Code:

printf "%s\n" "${array[@]}"


All times are GMT -5. The time now is 06:15 PM.