2. Array
• A data structure that can store a fixed-
size sequential collection of elements of
same type.
• More useful to think as a collection of
variables of the same type.
• Arrays we have consider up to now are
one dimensional arrays, a single line of
elements.
3. Programming Language Rating
90 85 85 90 80 20 20
95 90 85 80 90 30 10
C C++ C# java python ruby perl
Columns representing programming languages
Differentpersons
4. Why 2 D
• Matrix calculator
• Any kind of board game (chess, tic-tac-toe, number
puzzle, word puzzle, minesweeper etc.)
• Graph representation
• Image representation
• Excel data
• Database table to store information
etc………
6. Declaration
int x ; ///declaring integer type variable x
int x[100] ; ///declaring 1D array of 100 integers
7. Declaration
int x ; ///declaring integer type variable x
int x[100] ; ///declaring 1D array of 100 integers
int x[100] [50] ; ///declaring 100 1D array each of 50 integers
///i.e. a 2D array of 100 rows and 50 columns
8. Declaration
int x ; ///declaring integer type variable x
int x[100] ; ///declaring 1D array of 100 integers
int x[100] [50] ; ///declaring 100 1D array each of 50 integers
///i.e. a 2D array of 100 rows and 50 columns
datatype arrayName [Max_rows][Max_cols] ;
• datatype = any valid C data type.
• arrayName = any valid C identifier.
9. 2 D Array
int a[Max_rows] [Max_cols] ;
a[0][0] a[0][1] a[0][2] a[0][3]
a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]
Col 0 Col 1 Col 2 Col 3 Max_cols-1
Row 0
Row 1
Row 2
Max_rows-1
11. Accessing 2D array
1 2 3 4
5 6 7 8
9 10 11 12
Row 1 >>>
Col 1
int var=arr[1][1]; /// the value of variable var is 6
12. Accessing 2D array
1 2 3 4
5 6 7 8
9 10 11 12
Row 1 >>>
Col 1
int var=arr[1][1]; /// the value of variable var is 6
scanf("%d",&arr[2][3]); /// let, input is 100
printf("%d",arr[2][3]);
100
13. Accessing 2D array
1 2 3 4
5 6 7 8
9 10 11 12
Row 1 >>>
Col 1
int var=arr[1][1]; /// the value of variable var is 6
scanf("%d",&arr[2][3]); /// let, input is 100
arr[0][0] = 20 ;
printf("%d",arr[2][3]);
100
20
14. Taking Input
#include <stdio.h>
#define ROW 5
#define COL 3
int main()
{
int arr[ROW][COL];
int r,c;
for(r=0;r<ROW;r++){
for(c=0;c<COL;c++){
scanf("%d", &arr[r][c]);
}
}
printf("Completedn");
///other codes......
return 0;
}
15. Showing 2D array
int r,c;
for(r=0;r<ROW;r++){
for(c=0;c<COL;c++){
printf("%d ",arr[r][c]);
}
printf("n"); ///showing the next row in a different line
}