Arrays
Arrays
Arrays
Arrays
DR. MADHUSMITA SAHU
ASSOCIATE PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY
Array
An array is a consecutive series of variables that share one variable name.
The individual data items in an array must all be of the same data type.
Array elements are accessed using indexes or subscripts. Index starts from 0.
Arrays are mostly used when multiple variables of similar datatypes are processed
together.
Ordinary variable store one value at a time.
Arrays are used to store multiple values of similar datatype in a single variable name.
Also, known as a subscripted variable.
1
04-10-2024
Array
The array must be declared with datatype and maximum element before the use.
Each array element is referred to by specifying the array name followed by one or
more subscripts
◦ With each subscript enclosed in square brackets.
In Summary: Array
◦ Group of consecutive memory locations
◦ Same name and type
Arrays are used for storing more than one value at a time in a single variable name
2
04-10-2024
For Eg.
int number[30];
float marks[60];
char name[15];
Name of array
(Note that all
elements of this
array have the
1-D Array Declaration same name, c)
c[0] -45
To refer to an element, specify
c[1] 6
◦ Array name
c[2] 0
◦ Position number c[3] 72
c[4] 1543
Format:
c[5] -89
arrayname[ position number ]
c[6] 0
◦ First element at position 0
c[7] 62
◦ n element array named c: c[8] -3
◦ c[ 0 ], c[ 1 ]...c[ n – 1 ] c[9] 1
c[10] 6453
c[11] 78
Position number
of the element
within array c
3
04-10-2024
Integer Variable
int x = 30;
int y = 50;
int z = 70;
x y z
30 50 70
[2001] [101] [857]
Integer Array
int x[3] = {30,50,70};
Or,
4
04-10-2024
Initialization
1. int n[ 5 ] = { 1, 2, 3, 4, 5 };
This will create an array n with 5 elements and values 1,2,3,4 and 5.
2. int a[ 10 ] = { 0 };
This will create an array a with 10 elements all with value 0.
3. int n[ ] = { 1, 2, 3, 4, 5 };
If size omitted, initializers determine it automatically 5 values in {} so size will be 5.
4. int a[5]={1,2,3};
This will create array of 5 elements with values 1,2,3,0 and 0. ie if not sufficient values then rightmost
elements become 0.
5. int a[2][2]={{1,2},{3,4}};
This will create 2 dimensional array with 1,2,3,4 as element values.
Single Integer
a=5; 2005 5
5
04-10-2024
Integer Array
1 2 3 4 7 12 13 15 89 ……….
int my_array[20]={1,2,3,4,7,12,13,15,89};
char a;
a= ‘5’; 5
2006
6
04-10-2024
Character Array
C V R C E \0
char college_name[7]={‘C’,’V’,’R’,’C’,’E’,’\0’};
Visual representation
Offset
Address int x[4];
x[2]=23;
342901 ? 0 X Identifier
342905 ? 1
342909 23 2
342913 ? 3
Value
7
04-10-2024
Arrays
Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
Declaring Arrays
When declaring arrays, specify
◦ Name
◦ Type of array
◦ Number of elements
arrayType arrayName[ numberOfElements ];
◦ Examples:
int c[ 10 ];
float myArray[ 3284 ];
8
04-10-2024
Location of an element
Array of an element of an array say “A[ I ]” is calculated using the following formula:
Address of A [ I ] = B + W * I
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
Suppose we want to find out Loc (A [2]) in an integer array A[5].
For it, we have:
B=Base (A) = 1000
W = 2 bytes (Because an integer takes two bytes in the memory).
I=2
After putting these values in the given formula, we get:
LOC (A [2]) = 1000 + 2 * 2
= 1000 + 4
= 1004
9
04-10-2024
Example
Find average of ten marks.
#include<stdio.h>
main()
{
float avg,sum=0;
int i, mark[10];
for(i=0;i<10;i++)
{
printf(“Enter mark %d: ”,i+1);
scanf(“%d”,&mark[i]);
sum+=mark[i];
}
avg=sum/10;
printf(“\nAverage mark=%f”,avg);
}
10
04-10-2024
Array example
/* which type of integer is valid in array declaration*/
#include <stdio.h>
int main(void)
{
int x[5]; /* x[5] is array initialization /
x[0]=23; /* valid */
x[2.3]=5; /* invalid: index is not an int */
return 0;
}
Example Element
0
1
Value
19
3
Histogram
*******************
***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
/* Fig. 6.8: fig06_08.c 7 5 *****
Histogram printing program */ 8 17 *****************
#include <stdio.h> 9 1 *
#define SIZE 10
int main()
{
int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
int i, j;
printf( "\n" );
}
return 0;
}
11
04-10-2024
23
Example Enter a
string1
string2
string: Hello there
is: Hello
is: string literal
string1 with spaces between characters is:
1 /* Fig. 6.10: fig06_10.c H e l l o
12
04-10-2024
Examples
int x [5] = { 1,2,3,4,5 }; size 10 bytes
◦ creates array with elements 0-4 values 1-5
13
04-10-2024
Program to accept N
numbers and arrange
them in Ascending Order
14
04-10-2024
Output:
Program to find
Largest Element
In an Array
15
04-10-2024
Program to print
the second
smallest element
in an array
16
04-10-2024
Program to insert
an element at a
specified position
17
04-10-2024
1. Input size and elements in array. Store it in some variable say size and arr.
2. Input new element and position to insert in array. Store it in some variable say num
and pos.
3. To insert new element in the array, shift elements from the given insert position to
one position right. Hence, run a loop in descending order from size of array to pos to
insert. The loop structure should look like for(i=size; i>=pos; i--).
Inside the loop copy previous element to current element by arr[i] = arr[i - 1];.
4. Finally, after performing shift operation. Copy the new element at its specified
position i.e. arr[pos - 1] = num;.
18
04-10-2024
C program to search an
element in an array -
Linear Search
19
04-10-2024
Linear Search
2.Input number to be searched from user, store it in some variable say num.
4.Run a loop from 0 to size (where size is the total size of array).
5.Inside this loop check if array current value is equal to the number or not.
Which is if(arr[i] == num) then print element found successfully also make flag =
1 (means value has been found).
6.Finally after loop check if the flag contains original assigned value or new
value. Which is if(flag == 0) then print no elements found.
20
04-10-2024
21
04-10-2024
Binary Search
Binary search
• For sorted arrays
• Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Very fast; at most n steps, where 2n > number of
elements
30 element array takes at most 5 steps
25 > 30 so at most 5 steps
Binary Search
Binary search
• For sorted arrays
• Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Very fast; at most n steps, where 2n > number of elements
30 element array takes at most 5 steps
25 > 30 so at most 5 steps
22
04-10-2024
Example
/* C Program - Binary Search */ while (first <= last) {
#include<stdio.h> if(arr[middle] < search) {
first = middle + 1; }
int main() {
else if(arr[middle] == search) {
int n, i, arr[50], search, first, last, middle; printf("%d found at location %d\n",
printf("Enter total number of elements :"); search, middle+1);
break; }
scanf("%d“,&n);
else { last = middle - 1; }
printf("Enter %d number :", n); middle = (first + last)/2; }
for (i=0; i<n; i++) if(first > last) {
printf("Not found! %d is not present in
{ scanf("%d“,&arr[i]); }
the list .“ , search);
printf("Enter a number to find :"); }
scanf("%d", &search); return 0;
}
first = 0;
last = n-1;
middle = (first+last)/2;
Dimensionality
Determined by the number of subscripts of an array.
• x[i]
• y[i][j]
• z[i][j][k]
23
04-10-2024
Multiple-Subscripted Arrays
Multiple subscripted arrays
◦ Tables with rows and columns (m by n array)
◦ Like matrices: specify row, then column
Column subscript
Array name
Row subscript
47
Multiple-Subscripted Arrays
Initialization
◦ int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 2
Referencing elements 1 0
48
24
04-10-2024
Single Vs Multidimensional
Declaration: Declaration:
datatype name_of_array[20]; datatype name_of_array[20][20];
Initialization: Initialization:
name_of_array[20]={1,2,3,4……16}; name_of_array[20][20]={{1,2,3,4},
{2,3,4,5},{5,6,7,8}};
Initialising a 2D array
int b[2][2] = {{1}, {3, 4}};
• This one line will create a 2×2 array and
initialize the array as follows
Columns
0 1 Note: In this case, we
provide one data element
Rows
0 1 0 for the first row. After
this, all remaining elements
1 3 4 in the row are initialised
to 0
25
04-10-2024
Examples
• Assuming we have the following array b:
0 1
0 1 0
1 3 4
26
04-10-2024
Initialization:
1. int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
This will create an array b with 4 elements and values 1,2,3,4 . Values are grouped
by row in braces .
2. int b[ 3 ][ 2 ] = { { 1 }, { 3, 4 },{} };
This will create an array b with 6 elements with 1,0,3,4,0,0 values. If not enough
values, unspecified elements set to zero.
4. int myPoints[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
This will give error, 2nd dimension value is mandatory to be explicitly defined.
5. int a[2][2]={2};
This will create 2 dimensional array with 2,0,0,0 as element values.
Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
Representation of 2D Array
Array can be represented in sequential
memory using two ways.
1. Row Major Order
2. Column Major Order
27
04-10-2024
Example
Two Dimensional Array consist of 2 rows and 4 columns.
int A[2][4]
It can be stored sequentially in memory row by row.
2000 A[0][0]
2002 A[0][1]
Row 0
2004 A[0][2]
2006 A[0][3]
2008 A[1][0]
2010 A[1][1]
Row 1
2012 A[1][2]
2014 A[1][3]
28
04-10-2024
Location of an element
The Location of element A[i, j] can be obtained by evaluating expression:
LOC (A [i, j]) = Base_Address + W *[M * (i) + (j)]
Here,
Base_Address is the address of first element in the array.
W is the word size. It means number of bytes occupied by each element.
N is number of rows in array.
M is number of columns in array.
Example:
Suppose we want to calculate the address of element A [1, 2] in an array A[2][4]. Assume all elements
are integers. It can be calculated as follow:
Here, Base_Address = 2000, W = 2, M = 4, N = 2, i = 1, j = 2
LOC (A [i, j]) = Base_Address + W* [M* (i) + (j)]
LOC (A[1, 2]) = 2000 + 2 *[4*(1) + 2]
= 2000 + 2 * [4 + 2]
= 2000 + 2 * 6
= 2000 + 12
= 2012
29
04-10-2024
Example
Consider following example in which a two dimensional array consist of
two rows and four columns is stored sequentially in Column Major Order
as:
int A[2][4];
2000 A[0][0]
Column 0
2002 A[1][0]
2004 A[0][1]
Column 1
2006 A[1][1]
2008 A[0][2]
Column 2
2010 A[1][2]
2012 A[0][3]
Column 3
2014 A[1][3]
Location of an element
The Location of element A[i, j] can be obtained by evaluating expression:
LOC (A [i, j]) = Base_Address + W *[N *(j) + (i)]
Here,
Base_Address is the address of first element in the array.
W is the word size. It means number of bytes occupied by each element.
N is number of rows in array.
M is number of columns in array.
Example:
Suppose we want to calculate the address of element A [1, 2].It can be calculated as follow:
Here,
Base_Address = 2000, W= 2, M=4, N=2, i=1, j=2
LOC (A [i, j])=Base_Address + W *[N *(j) + (i)]
LOC (A[1, 2]) =2000 + 2 *[2*(2) + 1]
=2000 + 2 * [4 + 1]
=2000 + 2 * 5
=2000 + 10
=2010
30
04-10-2024
Example
//write a program to add two matrices for(i=0; i<r; i++)
for(j=0; j<c; j++) {
#include <stdio.h>
printf("Enter element a%d%d: ",i+1, j+1);
int main(){ scanf("%d", &b[i][j]); }
// Adding Two matrices
int r, c, a[100][100], b[100][100], sum[100][100], i, j; for(i=0;i<r;i++)
printf("Enter number of rows : "); for(j=0;j<c;j++) {
sum[i][j]=a[i][j]+b[i][j]; }
scanf("%d", &r); // Displaying the result
printf("Enter number of columns : "); printf("\nSum of two matrix is: \n\n");
for(i=0;i<r;i++)
scanf("%d", &c); for(j=0;j<c;j++) {
printf("\n Enter elements of 1st matrix:\n"); printf("%d ",sum[i][j]);
if(j==c-1) {
for(i=0; i<r; i++) printf("\n\n"); } }
return 0;}
for(j=0; j<c; j++) {
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d“,&a[i][j]); }
printf("Enter elements of 2nd matrix:\n");
31
04-10-2024
Mat-C
Explanation :
In matrix multiplication, all elements of xth row of matrix 1 is multiplied with
respective elements of yth column of matrix 2 and added together to find element
mul[x][y].
Example:
Mat-C[0][0] = Mat-A[0][0]*Mat-B[0][0]+ Mat-A[0][1]*Mat-B[1][0]
C Program to
Multiply matrices
32
04-10-2024
Example
printf("\nEnter elements of matrix 2:\n");
Program to multiply two matrix for(i=0; i<r2; ++i)
#include <stdio.h> for(j=0; j<c2; ++j) {
int main(){ printf("Enter elements b%d%d: ",i+1, j+1);
int a[10][10], b[10][10], c[10][10]={0}; scanf("%d",&b[i][j]); }
int r1, c1, r2, c2, i, j, k; // Multiplying matrices a and b and
printf("Enter rows and column for matrix1: "); // storing result in result matrix
scanf("%d %d", &r1, &c1); for(i=0; i<r1; ++i)
printf("Enter rows and column for matrix2: "); for(j=0; j<c2; ++j)
scanf("%d %d",&r2, &c2); for(k=0; k<c1; ++k) {
if (c1 != r2) result[i][j]+=a[i][k]*b[k][j]; }
printf(“multiplication not possible”); printf("\nOutput Matrix:\n");
else{ for(i=0; i<r1; ++i) {
printf("\nEnter elements of matrix 1:\n"); for(j=0; j<c2; ++j)
for(i=0; i<r1; ++i) printf("%d ", result[i][j]);
for(j=0; j<c1; ++j) { printf("\n\n"); }
printf("Enter elements a%d%d: ",i+1, j+1); }
scanf("%d", &a[i][j]); } return 0;
}
33
04-10-2024
Example
Program to find sum of diagonal elements of a square matrix
#include <stdio.h> for(i=0; i<m; i++){
int main(){ for(j=0; j<n; j++) {
int a[10][10], m,n,i, j, sum=0; if(i==j)
sum=sum+a[i][j];
printf("Enter rows and column for matrix1: "); }
scanf("%d %d", &m, &n); }
printf("\nEnter elements of matrix:\n"); printf(“\nSum of the diagonal elements
of a matrix is %d”,sum);
for(i=0; i<m; i++)
return 0;
for(j=0; j<n; j++) { }
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
Example
Program to count words ,spaces ,tab spaces ,characters in a given text.
#include<stdio.h>
int main(){
char st[80];
int sp=0,w=0,i=0,t=0;
printf(“enter a string”);
gets(st);
while(st[i]!=‘\0’) {
if(st[i]==‘\t’)
t=t+1;
if(st[i]==‘ ’)
sp=sp+1;
i++; }
w=sp+1;
printf(“Total spaces =%d”,sp);
printf(“Total words =%d”,w);
printf(“Total tab spaces =%d”,t);
printf(“Total characters =%d”,i);
return 0;
}
34
04-10-2024
2D-Array example
/*print Even and Odd no’s among 3x3 matrix/
#include<stdio.h>
main( )
{
int x, i, j, a[i][j], even=0, odd=1;
for( i=0;i<3; i++ )
{
for=0;j<3;j++ )
{
35
04-10-2024
36
04-10-2024
3D Array Initialization
int t[10][20][30]={
{/*Plane 0*/
{1,2,3,4}, /*Row 0*/
{5,6,7,8}, /*Row 1*/
{9,10,11,12} /*Row 2*/
},
{/*Plane 1*/
{21,22,23,24}, /*Row 0*/
{25,26,27,28}, /*Row 1*/
{29,30,31,32} /*Row 2*/
}
};
This array is a collection of 10 tables, each having 20 rows and 30 columns.
3D Array Initialization
t[0][0][0]=1 t[0][0][1]=2 t[0][0][2]=3 t[0][0][3]=4
t[0][1][0]=5 t[0][1][1]=6 t[0][1][2]=7 t[0][1][3]=8
t[0][2][0]=9 t[0][2][1]=10 t[0][2][2]=11 t[0][2][3]=12
t[1][0][0]=21 t[1][0][1]=22 t[1][0][2]=23 t[1][0][3]=24
t[1][1][0]=25 t[1][1][1]=26 t[1][1][2]=27 t[1][1][3]=28
t[1][2][0]=29 t[1][2][1]=30 t[1][1][2]=31 t[1][2][3]=32
All the remaining array elements will be assigned zeros.
37