Arrays in c
Arrays in c
Badharudheen P
Assistant Professor,
Dept. of CSE, MESCE, Kuttippuram
Introduction
❑ Arrays
❑ A collection of elements of the same type that are
referenced by a common name
❑ Compared to the basic data type (int, float & char) it is
an aggregate or derived data type
Arrays
❑ Consider the following case:
void main(void)
{
int studMark1, studMark2, studMark3, …,
…, …, studMark995, studMark996,
studMark997, studMark998, studMark999,
studMark1000;
…
…
}
Arrays
❑ By using an array, we just declare like this,
int studMark[1000];
❑ This will reserve 1000 contiguous memory locations for
storing the students’ marks.
Arrays
❑ We can use index/subscript to identify each element or
location in the memory.
❑ Hence, if we have an index of jIndex,
studMark[jIndex] would refer to the jIndexth
element in the array of studMark.
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
c[ 5 - 2 ] => c[ 3 ] => c[ x ]
Array Declaration
❑ When declaring arrays, specify
❑ Name
❑ Type of array
❑ Number of elements
❑ arrayType arrayName[numberOfElements];
❑ Examples:
❑ int c[ 10 ];
❑ float myArray[ 100 ];
int strlen(str);
❑ For eg:
int size;
char str[20];
size = strlen(str);
String Library Functions
❑ strcat: to concatenate two strings
strcat(str1, str2);
❑ concatenates str2 with str1
❑ For examples,
int a[3][4]; // 3 rows and 4 columns
float matrix[20][25]; //20 rows and 25 columns
Two Dimensional/2D Arrays
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
Two Dimensional/2D Arrays
❑ Initialization
1 2
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
3 4
1 0
❑ If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 3 4
❑ Referencing elements:
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
Two Dimensional/2D Arrays
❑ To assign initial string values for the 2D array