0% found this document useful (0 votes)
15 views34 pages

Arrays

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views34 pages

Arrays

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

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:

"We have a list of 1000 students' marks of an integer type. If


using the basic data type (int), we will declare something like
the following…"

int mark0, mark1, mark2, ..., mark999;


Arrays
 Can you imagine how long we have to write the declaration part by using normal
variable declaration?

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

data_type array_name [size] = {value1, value2, ...


valueN};
2. Array Initialization with Declaration
without Size

data_type array_name[] = {1,2,3,4,5};

The size of the above arrays is 5 which is automatically deduced by the compiler .

3. Array Initialization after Declaration (Using


Loops)
We initialize the array after the declaration by assigning the initial value to each element
individually. We can use for loop, while loop, or do-while loop to assign the value to each
element of the array.

for (int i = 0; i < N; i++) {


array_name[i] = valuei;
}
Access Array Elements

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,

char array_name[size] = "string_lateral_constant";

• For example, the array chVowel in the previous example could have been written
more compactly as follows,

char chVowel[6] = "aeiou";


Low-level languages High-level languages

• 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,

char chName[ ] = "Mr. Benny";

• 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,

int xNum[30], yNum[60];


float fPrice[25];
char charray[70];

• 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];

int studMark[] = {43,70,56,81,….,97}

 This will reserve 1000 contiguous


memory locations for storing the
students’ marks.
 Graphically, this can be depicted as in
the figure.
Reading/Printing elements in a 1
dimensional array from keyboard and
memory
• Declare an array of 5 integers
int marks[5];
• Read 5 integer values in an array
for (i=0; i<n; i++)
{
scanf(“%d”,&marks[i]);
}
• Printing values from an array
for (i=0; i<n; i++)
{
printf(“%d\t”, marks[i]);
}
Example C program – reading an array with ‘n’
elements; display all elements in given array.
Part-1 Part-2
#include <stdio.h> // display all elements in
void main() given array
{ for (i=0; i<n; i++)
int marks[100],n,i; {
printf("Enter the size of the printf(“%d\
array: "); t”,marks[i]);
scanf("%d",&n); }
printf("Enter %d elements of the }
array:\n",n); OUTPUT:
// read n elements in an array
for (i=0; i<n; i++)
{
scanf("%d“,&marks[i]);
}
Example C program – reading an array with ‘n’
elements;
find and display the sum of all elements in given
Part-2
array.
Part-1
// find sum of all elements in
#include <stdio.h>
void main() given array
{ for (i=0; i<n; i++)
int a[100],n,i,sum=0; {
printf("Enter the size of the sum += a[i];
array: "); }
scanf("%d",&n); // print sum
printf("Enter %d elements of printf("Sum of elements in given
the array:\n",n); array is %d\n",sum);
// read n elements in an }
OUTPUT:
array
for (i=0; i<n; i++)
{
scanf("%d“,&a[i]);
}
Example C program – reading an array with ‘n’
elements. Find and display the smallest of
given elements. Part-2
Part-1 // find smallest of all elements in given
#include <stdio.h> array
void main() for (i=1; i<n; i++)
{ {
int a[100],n,i,sum=0; if(a[i]<smallest)
printf("Enter the size of the array: ");
{
scanf("%d",&n);
printf("Enter %d elements of the smallest = a[i];
array:\n",n); }
// read n elements in an array }
for (i=0; i<n; i++) // print smallest
{ printf("Smallest of all given elements is %d\n",
scanf("%d“,&a[i]); smallest);
}
smallest = a[0]; OUTPUT:

}
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.

#include <stdio.h> Output


int main(void)
{
char array[5];
printf("array = %p\n&array[0] = %p\n &array = %p\
n",
array, &array[0], &array);
}
Passing arrays to functions - Example
Part-1 Part-2
#include <stdio.h> int main()
int searchElement(int arr[], int size, int x) {
{ int arr[] = {27, 5, 10, 2, 13, 15};
size--; int size = sizeof(arr) / sizeof(arr[0]);
if (size < 0) int x = 13;
{ int idx = searchElement(arr, size, x);
return -1; if (idx != -1)
} printf("Element %d is present at index
if (arr[size] == x) { %d",x,idx+1);
return size; else
} printf("Element %d is not present in the
return searchElement(arr, size, x); array",x);
} return 0;
}
Output

You might also like