Beruflich Dokumente
Kultur Dokumente
2-D Arrays
Nesting in Loops
Multidimensional Arrays
Arrays in C can have virtually as many dimensions as
you want.
Definition is accomplished by adding additional
subscripts when it is defined.
For example:
int a [4] [3] ;
defines a two dimensional array
a[0][0]
a[0][1]
a[0][2]
2-D Arrays
How to store these values?
1
4
7
10
2
5
8
11
3
6
9
12
};
3
12
printf(%d\t", a[row][col]);
printf(\n);
Output:
1
2
4
5
7
8
11
10
3
6
9
12
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int a[4] [3];
int row, col;
for (row = 0; row <=3; row++)
{
printf("Enter 3 elements of row %d\n", row + 1);
for (col = 0; col <=2; col++)
{
scanf("%d",&a[row][col]);
}
}
//Rest of the code goes here
Dr. Yousaf, PIEAS
Multiple-Subscripted Arrays
Multiple subscripted arrays
Tables with rows and columns (m by n array)
Like matrices: specify row, then column
Column 0 Column 1 Column 2 Column 3
Row 0
Row 1
Row 2
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 ]
Column subscript
Array name
Row subscript
Multiple-Subscripted Arrays
1
3
Initialization
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Initializers grouped by row in braces
If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
1
3
2
4
0
4
Multidimensional Arrays
Array declarations read right-to-left
int a[10][3][2];
an array of ten arrays of three arrays of two (type
ints). In memory
3
...
2
10
Maximum = marks[0];
for (i = 1; i <6;i++)
{
if (Maximum <marks[i])
{
Maximum = marks[i];
}
}
printf("Maximum Marks are
%d\n",Maximum);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
getch();
return 0;
}
int add[2][2];
int i, j;
printf("%d\t", add[i][j]);
}
}
getchar();
return 0;
}
Some Examples
//Linear Search
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in
array\n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
getchar();
return 0;
Sorting an Array
// Sorting an array in ascending
//order
#include <stdio.h>
int main()
{
int s, i ,j, temp, a[20];
printf("Enter total elements: ");
scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
for(i=0;i<s;i++)
{
for(j=i+1; j<s; j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("After sorting: \n");
for(i=0; i<s; i++)
printf(" %d",a[i]);
getchar(); return 0;
}