Mohamed Nuzhy Mohamed Nuzhy - 3 months ago 8
Linux Question

How can i write this kind of for loop in bash shell script?

here is the code i wrote in c language. But i don't know how to write this code in bash script. please, can anyone help me with this?

int d,k[2][2];
printf("enter the numbers:");
for(i=0;i<2;i++){for(j=0;j<2;j++){
scanf("%d",&k[i][j]);} //catch user input into 2D array
}

Answer

you can use this;

#!/bin/bash
declare -A array
n_rows=$1
n_columns=$2
for ((i=1;i<=n_rows;i++)) do
    for ((j=1;j<=n_columns;j++)) do
    read -p "Enter number [$i, $j] =  : " number
        array[$i,$j]=$number
    done
done

for ((j=1;j<=n_columns;j++)) do
    for ((i=1;i<=n_rows;i++)) do
        printf "%s " ${array[$i,$j]}
    done
    echo
done

Ex:

user@user-host:/tmp$ ./test.sh 2 2
Enter nuber [1, 1] : 1
Enter nuber [1, 2] : 2
Enter nuber [2, 1] : 3
Enter nuber [2, 2] : 4
        1        3
        2        4