Home > Blockchain >  storing the user input to 2D array
storing the user input to 2D array

Time:04-10

int n;
printf("Enter the amount of lines you want to print: ");
scanf("%d\n", &n);

int arr[n][n];

int a;
int b;
for (a=0; a<n; a  ){
    for(b=0; b<n ; b  ){
        scanf("%d", &arr[a][b]); 
    }
}
int a;
int b;
for (a=0; a<n; a  ){
    for(b=0; b<n ; b  ){
        scanf("%d", &arr[a][b]); 
    }
}

// My teacher suggested me to write something like this as a code to store input values in an 2D array, but the thing is I didn't understand how does it work. It seems like only storing values to [0][0], [1][1], [2][2] etc. Can someone help?

CodePudding user response:

It seems like only storing values to [0][0], [1][1], [2][2] etc.

No, it doesn't. It is storing values to:

[0][0], [0][1], ..., [0][n-1]

[1][0], [1][1], ..., [1][n-1]

...

[n-1][0], [n-1][1], ..., [n-1][n-1].

Because in your first (outer) loop, you are iterating through row indices, and then in the second (inner) loop, you are iterating through column indices for a fixed row index.

CodePudding user response:

The revised code doesn't compile due to redeclaration of a and b. Using printf in the 2nd loop:

#include <stdio.h>

int main() {
    int n;
    printf("Enter the amount of lines you want to print: ");
    scanf("%d\n", &n);

    int arr[n][n];
    for (int a=0; a<n; a  ){
        for(int b=0; b<n ; b  ){
            scanf("%d", &arr[a][b]);
        }
    }
    static const char sep[] = { ' ', '\n' };
    for (int a=0; a<n; a  ){
        for(int b=0; b<n ; b  ){
            printf("%d%c", arr[a][b], sep[b   1 == n]);
        }
    }
}

and an example session would be:

Enter the amount of lines you want to print: 2
1
2
3
4
1 2
3 4

CodePudding user response:

C does not store your array like this:

[0][0], [1][1], [2][2], ..., [n - 1][n - 1]

because the above representation only fills the array (table) diagonally, and rest of the cells will be left empty.

Instead, your array is filled like below:

[0][0], [0][1], ..., [0][n - 1]

[1][0], [1][1], ..., [1][n - 1]

...

[n - 1][0], [n - 1][1], ..., [n - 1][n - 1]

The above representation completely fills the table, every single cell. Have a look on these images diagonally and completely, in which n = 5.

Tips:

  • Your variables a, b and n should be of type size_t, read why?
  • Never re-define your variables with same name in same inner scope
  • Why aren't you are defining a and b in the for loop scope
  • Must check whether your scanf() input was successful or not by checking its return value
  • Initialize your 2-D array using = { }; [STACK AND FIXED LENGTH ONLY] or calling calloc() [HEAP ONLY]
  • Your array is of variable length, in this case storing data of heap memory is a good idea
  • I think you need to print the values of your 2-D array, so scanf() isn't made to do that use printf()
  • Related