Chapter 07 - Arrays - Students
Chapter 07 - Arrays - Students
1
Session Objectives
• To learn about array declaration and manipulation
• To learn about matrix operation using two dimensional arrays
• To learn about string handling using arrays.
2
Session Topics
• Accessing the array elements and array initialization
• Single and multidimensional array
• Strings and string variables: Reading and Printing a
string
• Functions and arrays
3
Why do we need an array?
Let’s consider the situation where we need to get 10 student’s age and
store it for some calculation.
Since age is an integer type, we can store it something like below,
Example:
int ag1, age2, age3, age4, age5, age6, age7, age8, age9, age10;
Arrays
main( )
{
int x ;
x=5;
x = 10 ;
printf ( "\nx = %d", x ) ;
}
• Ordinary variables (the ones which we have used so far) are capable of
holding only one value at a time.
• However, there are situations in which we would want to store more than
one value at a time in a single variable.
Arrays
• Marks of students
• 6 subjects
• 6 variable
• 24 hours
• 24 variables
• 100 students
• 100 variables
• For example, suppose we wish to arrange the percentage marks
obtained by 100 students in ascending order.
• In such a case we have two options to store these marks in
memory:
(a) Construct 100 variables to store percentage marks obtained by
100 different students, i.e. each variable containing one
student’s marks.
(b) Construct one variable (called array or subscripted variable)
capable of storing or holding all the hundred values.
Formal Definition of Array
An array is a collective name given to a group of ‘similar quantities’.
• An array lets you declare and work with a collection of values of the
same type. All elements of any given array must be of the same type. i.e.
we cannot have an array of 10 numbers, of which 5 are ints and 5 are
floats.
• For example, you might want to create a collection of five integers.
Example :int a, b, c, d, e;
• Using arrays it could be declared as below. int arr[5];
This reserves memory for an array that to hold five integer values
• Each member in the group is referred to by its position in the group. For
example, assume the following group of numbers, which represent
percentage marks obtained by five students. per = { 48, 88, 34, 23, 96 }
Formal Definition of Array
• per = { 48, 88, 34, 23, 96 }
• If we want to refer to the second number of the group, the usual notation
used is per2. Similarly, the fourth number of the group is referred as per4.
• However, in C, the fourth number is referred as per[3]. This is because
in C the counting of elements begins with 0 and not with 1. Thus, in this
example per[3] refers to 23 and per[4] refers to 96.
• In general, the notation would be per[i], where, i can take a value 0, 1, 2,
3, or 4, depending on the position of the element being referred. Here
per is the subscripted variable (array), whereas i is its subscript.
• Thus, an array is a collection of similar elements. These similar elements
could be all ints, or all floats, or all chars, etc. Usually, the array of
characters is called a ‘string’, whereas an array of ints or floats is called
simply an array.
Memory Allocation in Arrays
a[0] = 12;
a[1] = 9;
a[2] = 5;
a[3] = 14;
10
A Simple Program Using Array
A program to find average marks obtained by a class of 30 students in a
test.
main( )
{
int avg,
sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ; /* read data from an array*/
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}
Array Declaration
• To begin with, like other variables an array needs to be declared so
that the compiler will know what kind of an array and how large an
array we want.
• General syntax:, storage_class data_type array[expression];
• In our program we have done this with the statement: int marks[30] ;
• Here, int specifies the type of the variable, just as it does with
ordinary variables and the word marks specifies the name of the
variable. The [30] however is new.
• The number 30 tells how many elements of the type int will be in our
array. This number is often called the ‘dimension’ of the array. The
bracket ( [ ] ) tells the compiler that we are dealing with an array.
12
Accessing Elements of an Array
• Once an array is declared, individual elements in the array can be
referred.
• This is done with subscript, the number in the brackets following the
array name.
• This number specifies the element’s position in the array. All the array
elements are numbered, starting with 0. Thus, marks[2] is not the
second element of the array, but the third.
• In our program we are using the variable i as a subscript to refer to
various elements of the array. This variable can take different values
and hence can refer to the different elements in the array in turn. This
ability to use variables as subscripts is what makes arrays so useful.
Entering Data into an Array
• Here is the section of code that places data into an array:
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
• The for loop causes the process of asking for and receiving a student’s
marks from the user to be repeated 30 times.
• The first time through the loop, i has a value 0, so the scanf( ) function
will cause the value typed to be stored in the array element marks[0],
the first element of the array.
• This process will be repeated until I becomes 29. This is last time
through the loop, which is a good thing, because there is no array
element like marks[30].
• In scanf( ) function, we have used the “address of” operator (&) on the
element marks[i] of the array.
1. Write a program in C to store numbers and calculate the average of
the numbers using an array.
• Whatever there is initial values, all the array elements would always be
present in contiguous memory locations.
Bounds Checking
• Data entered with a subscript exceeding the array size will simply be
placed in memory outside the array; probably on top of other data, or
on the program itself.
• This will lead to unpredictable results, to say the least, and there will
be no error message to warn you that you are going beyond the array
size. In some cases the computer may just hang.
• Thus, the following program may be terminated or may crash.
main( ) {
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[i] = i ;
}
Initializing Arrays
• You can assign values to the array in several ways
• this example demonstrates
int main() {
int arrayOfInts1[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int arrayOfInts2[8];
int arrayOfInts3[ ] = {1,2,3,4,5,6,7,8}; /* an unsized array */
int arrayOfInts4[10];
int i; arrayOfInts2[0] = 1;
arrayOfInts2[1] = 2; • Till the array elements are not given any specific
arrayOfInts2[2] = 3; values, they are supposed to contain garbage
arrayOfInts2[3] = 4; values.
arrayOfInts2[4] = 5; • If the array is initialised where it is declared,
arrayOfInts2[5] = 6; mentioning the dimension of the array is optional
arrayOfInts2[6] = 7;
as in the 3rd example above.
arrayOfInts2[7] = 8;
for(i=0 ; i<8 ; i++)
= i + 1;
arrayOfInts4[i]
} return 0;
24
Reading Data from an Array
• One of the feature about array indexing is that, you can use a loop to
manipulate the index. For example, the following code initializes all of
the values in the array to 0:
int a[5];
int i;
for
(i=0;
i<5; i+
+)
a
[
i
]
0
;
• The following code initializes the values in the array sequentially and 25
then prints them out:
#include <stdio.h>
Example : READ and Display
#include <stdio.h>
#include <stdio.h>
int main()
int main() {
{
int a[5], i;
int a[5], i;
26
Example : READ, Process and Display
#include<stdio.h> else
void main( ) a[i]=a[i]*a[i];
{ }
int n,a[100]; for(i=0;i<n;i++)
int i; printf("a[%d]=%d\n",i,a[i]);
printf("How many numbers"); }
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{ if(i%2==0)
{
a[i]=a[i]+5;
}
27
Advantages of Arrays
•In an array, accessing an element is very easy by using the index number.
•2D Array is used to represent matrices.
• To store multiple values of similar type then the Array can be used and
utilized efficiently.
Disadvantages of Arrays
Array size is fixed: The array is static, which means its size is always
fixed. The memory which is allocated to it cannot be increased or
decreased.
int main()
{
int arr[10];
// Assign values to array
arr[0] = 5;
arr[5] = 6;
arr[7] = -9;
// Print array element at index 0
printf("Element at index 0 is %d\n",arr[0]);
return 0;
}
Element at index 0 is 5
Element at index 11 is -1176897384
Array is homogeneous: The array is homogeneous, i.e., only one type of
value can be store in the array. For example, if an array type “int“, can
only store integer elements and cannot allow the elements of other
types such as double, float, char so on.
35
Here is a program that prints out the memory locations in which the
elements of this array are stored.
Operation on Arrays
1. Traversal
2. Copying
3. Reversing
4. Insertion
5. Sorting
6. Deletion
7. Searching
8. Merging
Sorting elements of an array
Step 1: Input the size of the array arr[] and declare the variables.
Step 2: Use a loop to insert the elements in an array.
Step 3: Now, input the position of the particular element that the user or programmer
wants to delete from an array. For user location starts from position 1. However array
index starts from 0. Hence, when we delete the element we need to delete element
present at location = position -1.
Step 4: Compare the position of an element (pos) from the total no. of elements
(num+1). If the pos is greater than the limit, the deletion of the element is not possible
and jump to step 7.
Step 5: Else removes the particular element and shift the rest elements' position to the
left side in an array. What we essentially do is, shift the element next to the element to
be deleted to the location = position -1, i.e. the next element is placed in position of
deleted element and so on we keep shifting the remaining elements by one position to
the left.
Step 6: Display the resultant array after deletion or removal of the element from an
array.
Step 7: Terminate or exit from the program.
printf("Enter the location from where you wish to delete the element:\n");
scanf("%d", &position);
num = array[position-1];
if (position >= n+1 || position < 0) /*n+1, since user will count element as
position 1 onwards. Internally though indexing starts from 0, which user would
not know.*/
printf("Deletion not possible as entered location is invalid.\n");
else
{
for (i = position - 1; i < n - 1; i++) //since array index starts from 0; thus position
in terms of array index is position-1
array[i] = array[i+1];
printf("Resultant array after deletion of element %d from location %d:\n", num,
position);
for (i = 0; i < n - 1; i++)
printf("%d\n", array[i]);
}
return 0;
}
Searching element of an array
We accept the array input from user.
The user will enter the element that needs to be searched in the
array.
We scan the entire array sequentially to search for entered element
‘num‘.
On discovering the element in the array at location i, we display it
to the user.
If the element occurs at more than one place as well, the search
continues until end of array is reached.
If even after scanning entire array element is not found, ( i==n) then
same is conveyed to user.
int array[100], num, i, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements: \n");
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter a number to search\n");
scanf("%d", &num);
for (i = 0; i < n; i++)
{
if (array[i] == num) /* When required element is found */
{
printf("The element: %d is present at location %d.\n", num, i+1);
}
if (i == n)
printf("The element %d is not present in the array.\n", num);
return 0;
}
Merging of two arrays
Copy the elements of the first array to the merged array when
initialising it.
Copy the elements of the second array to the merged array while
initialising the second array.
50
GPA Calculation
#include <stdio.h>
#define nsub 6
main()
{
int grade_pt[nsub], cred[nsub],i, gp_sum=0, cred_sum=0, gpa;
printf(“Input gr. points and credits for six subjects \n”);
for (i=0; i<nsub; i++)
scanf(“%d %d”, &grade_pt[i], &cred[i]);
for (i=0; i<nsub; i++)
{
gp_sum += grade_pt[i] * cred[i];
cred_sum += cred[i];
}
gpa= gp_sum / cred_sum;
printf(“\n Grade point average: is
%d”, gpa);
}
51
#include <stdio.h>
void main()
{ int arr1[100];
int n, i, j, tmp;
printf("\n\nsort elements of array in ascending order :\n ");
printf("----------------------------------------------\n");
printf("Input the size of array : ");
scanf("%d", &n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{ printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr1[j] <arr1[i])
{
tmp = arr1[i]; arr1[i] = arr1[j]; arr1[j] = tmp;
}
}
}
printf("\nElements of array in sorted ascending order:\n");
for(i=0; i<n; i++)
{
printf("%d ", arr1[i]);
}
printf("\n\n");
}
#include <stdio.h>
void main ()
{
Syntax:
int x[i][j];
Elements in two-dimensional arrays are commonly referred to by x[i][j]
where i is the row number and ‘j’ is the column number.
54
2-D Array
•We have seen that an array variable can store a list of values.
•Many applications require us to store a table of values.
55
2-D Array
• A two – dimensional array can be seen as a table with ‘x’ rows and
‘y’ columns where the row number ranges from 0 to (x-1) and the
column number ranges from 0 to (y-1).
56
Memory Map of a 2-Dimensional Array
Col 0 Col 1 Col 2 Col 3 Col 4
Row 0 75 82 90 65 76
Row 1 68 75 80 70 72
Row 2 88 74 85 76 80
Row 3 50 65 68 40 70
S[0][0] S[0][1] S[0][2] S[0][3] S[0][4] S[1][0] S[1][1] S[1][2] S[1][3] S[1][4] S[2][0] S[2][1] S[2][2] S[2][3] S[2][4] S[3][0] S[3][1] S[3][2] S[3][3] S[3][4]
75 82 90 65 76 68 75 80 70 72 88 74 85 76 80 50 65 68 40 70
Memory Map of a 2-Dimensional Array
• Let us repeat the arrangement of array elements in a two-dimensional
array of students, which contains roll nos. in one column and the marks
in the other.
• We can easily refer to the marks obtained by the third student using the
subscript notation as shown below:
printf ( "Marks of third student = %d", stud[2][1] ) ;
Declaring 2-D Arrays
General form:
storage_class data_type array_name [row_size][column_size];
•Examples:
int marks[4][5];
float sales[12]
[25];
double matrix[100][100];
static double matrix[100]
[100];
• Accessing Elements of a 2-D Array
• Similar to that for 1-D array, but
use two indices.
–First indicates row, second
indicates column.
- Both the indices should be expressions which evaluate to
integer values.
59
Initialising a 2-Dimensional Array
int stud[4][2] = { { 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
or even this would work...
int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;
of course with a corresponding loss in readability.
There are two parts to the program—in the first part through a for loop we
read in the values of roll no. and marks, whereas, in second part through
another for loop we print out these values.
Example : Addition of two Matrices
/* Stored values into the array*/
printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}
#include<stdio.h>
main() Example : Matrix Addition
{
int a[100][100], b[10][10], c[10][10], p, q, m, n;
printf("\n Enter row and col:");
scanf("%d %d", &m, &n);
printf("\n Matrix A");
for (p=0; p<m; p++)
{
for (q=0; q<n; q++) {
printf("\n Enter element %d and %d: ", p, q);
scanf("%d", &a[p][q]);
}
}
printf("\n Matrix B");
for (p=0; p<m; p++) printf("\n Matrix B");
{ for (p=0; p<m; p++)
for (q=0; q<n; q++) { {
printf("\n Enter element %d and %d: ", p, q); printf ("\n|");
scanf("%d", &b[p][q]); for (q=0; q<n; q++)
} {
} printf(" %d ", c[p][q]);
printf("\n Matrix Addition");
for (p=0; p<m; p++) }
for (q=0; q<n; q++) printf("|");
c[p][q]=a[p][q]+b[p][q]; }
}
What will be the output of the following programs:
# include <stdio.h>
int main( )
{
int num[ 26 ], temp ;
num[ 0 ] = 100 ;
num[ 25 ] = 200 ;
temp = num[ 25 ] ;
num[ 25 ] = num[ 0 ] ;
num[ 0 ] = temp ;
printf ( "%d %d\n", num[ 0 ],
num[ 25 ] ) ;
return 0 ;
}
200 100
# include <stdio.h>
int main( )
{
int array[ 26 ], i ; 65 A
for ( i = 0 ; i <= 25 ; i++ ) 66 B
{ .
array[ i ] = 'A' + i ; .
printf ( "%d %c\n", array[ i ], .
array[ i ] ) ; .
} .
return 0 ; 90 Z
}
# include <stdio.h>
int main( )
{
int sub[ 50 ], i ; 49 49
for ( i = 0 ; i <= 48 ; i++ ) ;
{
sub[ i ] = i ;
printf ( “%d %d\n",i, sub[ i ] ) ;
}
return 0 ;
}
# include <stdio.h>
int main( ) {
int size ;
scanf ( "%d", &size ) ;
int arr[ size];
for ( i = 1 ; i <= size ; i++ ) {
scanf ( "%d", &arr[ i ] ) ;
printf ( "%d\n", arr[ i ] ) ;
}
return 0 ;
}
‘i’ undeclared
# include <stdio.h>
int main( )
{
int array[ 6 ] = { 1, 2, 3, 4, 5, 6 } ;
int i ;
for ( i = 0 ; i <= 25 ; i++ )
printf ( "%d\n", array[ i ] ) ;
1
return 0 ;
2
}
3
4
5
6
634427648
2031456649
Array bounds
exceeded
# include <stdio.h>
int main( )
{
int n[ 3 ][ 3 ] = {
2, 4, 3,
6, 8, 5,
3, 5, 1
};
printf ( " %d %d\n", n[ 2 ][ 0 ], n[ 2 ][ 2 ] ) ;return 0 ;
}
3 1
# include <stdio.h>
int main( )
{
int sub[ 50 ], i ;
for ( i = 0 ; i <= 50 ; i++ )
{
sub[ i ] = i ;
1
printf ( "%d\n" , sub[ i ] ) ;
2
}
3
return 0 ;
4
}
5
6
.
.
50
Terminated:
Array bounds
# include <stdio.h>
int main( )
{
int three[ 3 ][ ] = {
2, 4, 3,
6, 8, 2,
2, 3, 1
};
printf ( "%d\n", three[ 1 ][ 1 ] ) ;
return 0 ;
}
d=b+++a;
printf(“%d %d %d %d”,a,b,c,d);
}
15 12 -4 26
# include <stdio.h>
int main()
{
int x = 10;
{
int x = 0;
printf("%d",x);
}
return 0;
}
0
#include <stdio.h>
void main()
{
int i = 2,j=0;
{
int i = 4, j = 5;
printf("%d %d", i, j);
}
printf("%d %d", i, j);
}
4 52 0
#include <stdio.h>
void main()
{
int i = 2;
{
int i = 4, j = 5;
printf("%d %d", i, j);
}
printf("%d %d", i, j);
}
{
/*OUTER BLOCK*/
//contents of the outer block just before the start of this block
//CAN be accessed here
/*INNER BLOCK*/
infinite loop