Arrays
Arrays
Arrays ‐ Background/Overview
Arrays
• An array is 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.
• All the elements of an array occupy a set of contiguous memory locations.
Arrays
• Why need to use array type?
• Consider the following issue:
int main(void)
{
int marks0, marks1, marks2, marks3, marks4, …, …, marks998,
marks999;
…
…
return 0;
}
Array Declaration Syntax of Array
Declaration
// C Program to illustrate the array declaration
#include <stdio.h> data_type array_name [size];
or
int main() data_type array_name [size1] [size2]...
{ [sizeN];
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}
1. Array Initialization with Declaration
The size of the above arrays is 5 which is automatically deduced by the compiler .
array_name [index];
Types of Arrays
• One-Dimensional Array
• Two-Dimensional Array
• Multi-Dimensional Array
Single dimension arrays
• Dimension refers to the array's size, which is how big the array is.
• A single or one dimensional array declaration has the following form,
array_element_data_type array_name[array_size];
• Here, array_element_data_type define the base type of the array, which
is the type of each element in the array.
• array_name is any valid C identifier name that obeys the same rule for
the identifier naming.
• array_size defines how many elements the array will hold.
Arrays ‐ Initialization
• An array may be initialized at the time of declaration.
• Giving initial values to an array.
• Initialization of an array may take the following form,
type array_name[size] = {a_list_of_value};
• For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i',languages
Low-level 'o', 'u', '\0'};
• The first line declares an integer array idNum and it immediately assigns the values 1, 2,
3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.
• The second
First Generation
line assigns the values 5.6 to FloatNum[0], 5.7 toFourth
fFloatNum[1],
Generation and so on.
• Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1], and so on.
Note again, for characters we must use the single apostrophe/quote (') to enclose them.
• Also, the last character in chVowel is NULL character ('\0').
Arrays ‐ Initialization
• Initialization of an array of type char for holding strings may take the following
form,
• For example, the array chVowel in the previous example could have been written
more compactly as follows,
• When the value assigned to a character array is a string (which must be enclosed
in double quotes), the compiler automatically supplies the NULL character but we
still have to reserve one extra place for the NULL. Fourth Generation
• For unsized array (variable sized), we can declare as follow,
• C compiler automatically creates an array which is big enough to hold all the
Single dimension arrays
• In this statement, the integer
• For example, to declare an array of 5 character can store up to 5 marks
marks, that construct a mark list, we with the first mark occupying
could declare, location marks[0] and the last
int marks[5]; character occupying marks[4].
• which can be depicted as follows, • Note that the index runs from 0 to
4. In C, an index always starts from
0 and ends with array's (size-1).
• So, take note the difference
between the array size and
subscript/index terms.
Single dimension arrays
• Examples of the one-dimensional array declarations,
• The first example declares two arrays named xNum and yNum of type int. Array
xNum can store up to 30 integer numbers while yNum can store up to 60
numbers.
• The second line declares the array fPrice of type float. It can store up to 25
floating-point values.
• The third line declares the array charray of type char. It can store a string up to
69 characters.
• Why 69 instead of 70? Remember, a string has a null terminating character (\0)
at the end, so we must reserve for it.
Declaring and initializing an array
By using an array, we just declare like
this,
int studMark[1000];
}
Two dimension arrays - declaration
A 2D array is also known as a matrix (a table of rows and columns).
A two dimensional array declaration has the following form,
array_element_data_type array_name[no_rows][no_cols];
Here, array_element_data_type define the base type of the array, which is the type
of each element in the array.
array_name is any valid C identifier name that obeys the same rule for the identifier
naming.
no_rows (1st dimension) defines how many rows the array will have and no_cols (2 nd
dimension) defines how many columns the array will have.
Two dimension arrays -
initialization
• To create a 2D array of integers, take a look at the following example:
int Array[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
• The first dimension represents the number of rows [2], while the second dimension
represents the number of columns [3].
Reading/Printing elements in a 2 dimensional
array from keyboard and memory
• Printing values from a 2D array
• Declare a 2D array of 3 rows and 3
// row values from 0 to 2
columns of type integers
for (i=0; i<n; i++)
int Array[3,3];
{
• Read integer values in a 2D array
// columns values from 0 to 2
// row values from 0 to 2
for (j=0;j<2; j++)
for (i=0; i<n; i++)
{
{
printf(“%d\t”,Array[i]
// columns values from 0 to 2
[j]);
for (j=0;j<2; j++)
}
{
printf(“\n”);
scanf(“%d”,&Array[i][j]);
}
}
}
Example C program – reading and display
elements in a M X N matrix
Part-2
Part-1
// display all elements in matrix
#include <stdio.h>
printf("The elements in the given two dimensional
void main()
array are:\n");
{
for (i=0; i<row; i++)
int Matrix[10][10],row,col,i,j;
{
printf("Enter the number of rows: ");
for(j=0; j<col; j++)
scanf("%d",&row);
{
printf("Enter the number of columns: ");
printf("%d\t",Matrix[i][j]);
scanf("%d",&col);
}
printf("Enter %d elements of the array:\
printf("\n");
n",row*col);
}
// read n elements in a matrix
for (i=0; i<row; i++)
}
{
for(j=0; j<col; j++)
{ OUTPUT:
scanf("%d",&Matrix[i][j]);
}
}
Example C program – reading two 3X3 matrices and
display resultant matrix which is the addition of
given two matrices
Part-1
#include <stdio.h> Part-2
void main() // read n elements in
{ second matrix
int Matrix1[10][10], Matrix2[10][10], printf("Enter 9 elements in
Matrix3[10][10];
second matrix\n");
int row,col,i,j;
// read n elements in first matrix for (i=0; i<3; i++)
printf("Enter 9 elements in first matrix\ {
n"); for(j=0; j<3; j++)
for (i=0; i<3; i++) {
{
for(j=0; j<3; j++) scanf("%d",&Matrix2[i][j]);
{ }
scanf("%d",&Matrix1[i]
}
[j]);
}
}
OUTPUT:
Example C program – reading two 3X3 matrices and
display resultant matrix which is the multiplication
of Part-1
given two matrices
Part-2
#include <stdio.h>
// read n elements in second
void main()
matrix
{
printf("Enter 9 elements in
int Matrix1[10][10], Matrix2[10][10],
second matrix\n");
Matrix3[10][10];
for (i=0; i<3; i++)
int row,col,i,j;
{
// read n elements in first matrix
for(j=0; j<3; j++)
printf("Enter 9 elements in first matrix\
{
n");
for (i=0; i<3; i++)
scanf("%d",&Matrix2[i][j]);
{
}
for(j=0; j<3; j++)
}
{
scanf("%d",&Matrix1[i]
[j]);
}
}
Part-3
// multiply the given two matrices
OUTPUT:
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{
Matrix3[i][j]=0;
for(k=0;k<3;k++)
{
Matrix3[i][j]+=Matrix1[i]
[k]*Matrix2[k][j];
}
}
} // display all elements in matrix
printf("The resultant matrix is:\n");
for (i=0; i<3; i++)
{ for(j=0; j<3; j++)
{
printf("%d\t",Matrix3[i][j]);
}
printf("\n");
}
}
Two Dimensional 2D Arrays
• If we assign initial string values for the 2D array it will look something like the
following,
• char Name[6][10] = {“Abhijeet", “Amar", “Bushra", “Deepa", “Francis", “Vinay"};
• Here, we can initialize the array with 6 strings, each with maximum 9 characters
long.
• If depicted in rows and columns it will look something like the following and can be
considered as contiguous arrangement in the memory.
Transpose of a Matrix- Example
#include<stdio.h> Part-2
int main(){ for(int i=0; i<m; i++){
int m, n; for(int j=0; j<n; j++){
int temp = matrix[i][j];
printf("Enter the number of rows: "); matrix[i][j] = matrix[j][i];
scanf("%d", &m); matrix[j][i] = temp;
printf("Enter the number of columns: }
"); }
scanf("%d", &n); printf("The transposed matrix is:\n");
int matrix[10^5][10^5]; for(int i=0; i<n; i++){
printf("Enter the elements of the mat for(int j=0; j<m; j++){
rix:\n"); printf("%d ", matrix[i][j]);
Output for(int i=0; i<m; i++){ }
Enter the numberfor(int
of rows: 3 j=0; j<n; j++){ printf("\n");
Enter the number of columns: 2
scanf("%d", &matrix[i]
Enter the elements of the matrix:
}
12 [j]); } } return 0;
23
34
}
The transposed matrix is:
123
234
Multi dimensional arrays
• For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the number of
the colored square. In general, for
array_name[x][y];
• The array size is = First index x second index = xy.
• This also true for other array dimension, for example three dimensional array,
array_name[x][y][z]; => First index x second index x third index = xyz
• For example,
ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
• And if you want to illustrate the 3D array, it could be a cube: width, length and height
dimensions.
Passing arrays to functions
• To pass an array argument to a function, specify the array’s name without any
brackets.
• For example, if array hourlyTemperatures has been defined as
int hourlyTemperatures[HOURS_IN_A_DAY];
• the function call
modifyArray(hourlyTemperatures, HOURS_IN_A_DAY)
• passes array hourlyTemperatures and its size to function modifyArray.
Passing arrays to functions
• Below program demonstrates that “the value of an array name” is really the address
of the first element of the array by printing array, &array[0] and &array using the %p
conversion specifier for printing addresses.
• The %p conversion specifier normally outputs addresses as hexadecimal numbers,
but this is compiler dependent.