Two Dimensional Array in C
A two-dimensional (2D) array is a multi-dimensional data structure that stores data in rows and columns, similar to a table or matrix.This is a simple C program that demonstrates how to work with a 2D array and iterate through its elements to print them.
Example : print_2darray.c
#include <stdio.h> int main() { int rows, cols; // Input dimensions of the 2d array printf("Enter the number of rows: "); scanf("%d", &rows); printf("Enter the number of columns: "); scanf("%d", &cols); int array[rows][cols]; // Input elements of the 2d array printf("Enter the elements of the 2D array:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element at [%d][%d]: ", i, j); scanf("%d", &array[i][j]); } } // Print the 2d array printf("\nThe 2D array is:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", array[i][j]); } printf("\n"); } return 0; }
Output:
Enter the number of rows: 2
Enter the number of columns: 3
Enter the elements of the 2D array:
Enter element at [0][0]: 1
Enter element at [0][1]: 2
Enter element at [0][2]: 3
Enter element at [1][0]: 4
Enter element at [1][1]: 5
Enter element at [1][2]: 6
The 2D array is:
1 2 3
4 5 6
Enter the number of columns: 3
Enter the elements of the 2D array:
Enter element at [0][0]: 1
Enter element at [0][1]: 2
Enter element at [0][2]: 3
Enter element at [1][0]: 4
Enter element at [1][1]: 5
Enter element at [1][2]: 6
The 2D array is:
1 2 3
4 5 6