Introduction to C
Data Types in C
Operators in C
Hello World Program
Loops in C
Single Dimensional Array
Two Dimesnional Arrays
Array Example Programs
In the previous chapters, we learned about single dimension arrays. Herein this chapter, we shall learn two dimensional (Bi-dimensional) arrays and multi-dimensional arrays.
In single dimension arrays, we were storing a set of characters or integers or a string. But what if we have to store multiple strings in an array. For example, we have to store 10 names with maxlength of 20 characters each. This is not possible in single dimension array. It will be in two dimensional array. It will be something like:
It will represent an array for 10 names with maxlength of 20 characters each. But this is two dimensional array. It can also be supposed as a matrix as here, there are 10 rows and 20 columns.
Similarly, if we have to represent names with address also, then it will be tri-dimensional array or multi-dimensional array. It will be like:
Here, we will see two dimensional arrays only. Lets understand it with the help of a program.
C Program to input a two dimensional array from user and print it
Enter matrix of 3*3 : 5 7 8 4 9 1 2 4 6
Matrix you entered is :
5 7 8
4 9 1
2 4 6
A two-dimensional array is defined as int a. It means there will be a two-dimensional array named 'a' which has 3 rows and 3 columns. Two more integer variables i and j are taken. Then the printf statement will print whatever it has (Enter matrix of 3*3:). Now as we have to input a two-dimensional array from user then we have to use two for loops, one for rows and one for columns. Just like we have used one for loop in single dimensional array because there is a row only but not columns.
So, firstly i=0 and i<3 condition will be true and it goes inside first for loop. There, it finds again a second for loop which will check the condition i<3 which is also true. In that case it will take input as a. It means the value at first row and first column. Similarly all 9 values will be taken as input from user using for loop as the condition will satisfy till i<3. Now, these values are printed using the printf statement.
Note: If find any issues/errors with the tutorial above, please immediately mail it to email@example.com