Unit II Arrays
Unit II Arrays
Unit II Arrays
As the number of variables increases, the complexity of the program also increases and so the
programmers get confused with the variable names. There may be situations where we need to work
with a large number of similar data values.
C programming language provides an amazing feature to deal with such kind of situations that is
known as "Arrays".
An "Array" is a group of similar data type to store series of homogeneous pieces of data that all are
same in type.
It is a derived data type which is created with the help of basic data type. An array takes contiguous
memory blocks to store series of values.
Syntax for creating an array without size and with initial values
In the above syntax, the datatype specifies the type of values we store in that array and size specifies
the maximum number of values that can be stored in that array.
int a[3];
Here, the compiler allocates 12 bytes of contiguous memory locations with a single name 'a' and tells
the compiler to store three different integer values (each in 4 bytes of memory) into that 12 bytes of
memory. For the above declaration, the memory is organized as follows...
arrayName [ indexValue ] ;
For example, if we want to assign a value to the second memory location of above array 'a', we use
the following statement..
a[1]=100
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1]
will be 2124d. Similarly, the address of mark[2] will be 2128d and so on.
This is because the size of a int & float is 4 bytes.
Initialize an array
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
int main() {
int values[5],i;
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
scanf("%d", &n);
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output:
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
Now let's say if you try to access testArray[12]. The element is not available. This may
cause unexpected output (undefined behaviour). Sometimes you might get an error and some
other time your program may run correctly.
Hence, you should never access elements of an array outside of its bound.
Linear Search
Binary Search
Step by step descriptive logic to search element in array using linear search algorithm.
1. Input size and elements in array from user. Store it in some variable say size and arr.
2. Input number to search from user in some variable say toSearch.
3. Define a Count variable as Count = 0. I have initialized count with 0, which means
initially I have assumed that searched element does not exists in array.
4. Run loop from 0 to size. Loop structure should look like
for(i=0; i<size; i++).
5. Inside loop check if current array element is equal to searched number or not. Which
is if(arr[i] == toSearch) then set count = 1 and terminate from loop. Since
element is count no need to continue further.
Outside loop if(count == 1) then element is found otherwise not.
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, count;
/*
* If element is not found in array
*/
if(count == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array", toSearch);
}
return 0;
}
Sorting is a process by which we can arrange the elements in a specific order. The order may
increasing or decreasing. By default it is increasing. There are several algorithm are available
to sort an array. They are
Bubble sort
Selection sort
Insertion sort
Bubble sort
Bubble Sort in C is a sorting algorithm where we repeatedly iterate through the array and
swap adjacent elements that are unordered. We repeat this until the array is sorted.
How Bubble Sort Works?
1) Starting from the first index, compare the first and the second elements. If the first
element is greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if they are not in order.
The above process goes on until the last element.
2) The same process goes on for the remaining iterations. After each iteration, the largest
element among the unsorted elements is placed at the end.
In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct
positions.
1. Input size of array and elements in array. Store it in some variable say size and arr.
2. To select each element from array, run an outer loop from 0 to size - 1. The
loop structure must look like for(i=0; i<size; i++).
3. Run another inner loop from i + 1 to size - 1 to place currently selected
element at its correct position. The loop structure should look like
for(j = i + 1; j<size; j++).
4. Inside inner loop to compare currently selected element with subsequent element
and swap two array elements if not placed at its correct position.
Which is if(arr[i] > arr[j]) then swap arr[i] with arr[j].
#include <stdio.h>
int main()
{
int size;
int i, j, temp;
#include <stdio.h>
int main()
{
int size;
int i, j, temp,min,p;
}
/* After successful sort elements in array */
printf("After sorting elements in array: ");
for(i=0; i<size; i++) {
printf("%d\t", arr[i]);
}
Insertion sort
The basic theory of the this sorting tehnique is that each element is inserted into its proper
position in a previously sorted array. The process starts from the 2 nd element of the array.
Before this initially considered a single element only and it can be considered as asorted array
which has only one element. Now considered two elements form an array i.e. upto 2nd
element into array, check the 2nd elements is in proper position or not compare with previous
element. If it not insert into proper position. Consideered three elements, already two
elements are sorted, now check new elements in proper position or not if it not compare with
adjecent and previous elements and set into proper position. Now considered four elements
continue same process. This process will repeted untill all emenets are set into proprer
position. This process is called Insertion sorting, because we inserting an elemnts into proper
position.
Example:
#include<stdio.h>
void main()
{
int i,j,k,temp,n;
printf("Enter how many elements you want giving");
scanf("%d",&n);
int array[n];
for(i=0;i<n;i++)
scanf("%d",&array[i]);
printf("The Array Elements are\n");
for(i=0;i<n;i++)
printf("%d\t",array[i]);
for(i=0;i<n-1;i++){
j=i;
if(array[j]>array[j+1])
{ back:
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp; Sorting
} Logic
if(i>0&&array[j-1]>array[j])
{
j=j-1;
goto back;
}
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d is present at index %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
return 0;
}
Output:
Enter number of elements in array
4
Enter 4 elements
Enter 0 elements
9
Enter 1 elements
8
Enter 2 elements
7
Enter 3 elements
6
Enter the location where you wish to insert an element
0
Enter the value to insert
10
Resultant array is
10
9
8
7
6
C program to deletion an element in an array, for example, consider an array a[10] having ten
elements in it initially and a[0] = 10, a[1] = 20 a[2] = 30, a[3] = 40…… and a[9] = 100 and you
want to delete an element at location 1 i.e. a[0] = 10, so we have to remove elements at a[0].
Then we copy the elements a[1] to a[0], a[2] to a[1] and so on.. And finally reduce the no. of
elements in an array. Array deletion does not mean decreasing its size i.e array will contain
09 elements.
#include <stdio.h>
#define SIZE 100
int main()
{
int arr[SIZE];
int i, n, pos,j;
int main()
{
int i, n;
float arr[100];
return 0;
}
Example: C program for Reverse array
#include <stdio.h>
int main()
{
int n, i, j;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
int arr1[n], arr2[n];
return 0;
}
Output:
Enter the number of elements in array
4
Enter array elements
Enter the arr1[0] element 9
Enter the arr1[1] element 8
Enter the arr1[2] element 7
Enter the arr1[3] element 6
The array elements are
9 8 7 6
After Reverse The array elements are
6 7 8 9
Example: C program for second Largest elements in an array
#include <stdio.h>
#include <limits.h> // For INT_MIN
int main()
{
int arr[MAX_SIZE], size, i;
int max1, max2;
/*
* Check for first largest and second
*/
for(i=0; i<size; i++)
{
if(arr[i] > max1)
{
/*
* If current element of the array is first largest
* then make current max as second max
* and then max as current array element
*/
max2 = max1;
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
/*
* If current array element is less than first largest
* but is greater than second largest then make it
* second largest
*/
max2 = arr[i];
}
}
return 0;
}
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the
array as a table with 3 rows and each row has 4 columns.
float y[2][4][3];
Initialization of a 2d array
// Different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
Initialization of a 3d array
You can initialize a three-dimensional array in a similar way like a two-dimensional array.
Here's an example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Output:
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Output:
Enter elements of 1st matrix
Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
int main()
{
int m, n, i, j, temp;
return 0;
}
int main()
{
int m, n, i, j, matrix[10][10], transpose[10][10];
return 0;
}
#include<stdio.h>
int main()
{
int m, n, i, j, matrix[10][10], transpose[10][10];
return 0;
}
Output:
Enter the number of rows and columns of matrix
3
3
Enter elements of the matrix
Inverse of Matrix
This is a c program to find the inverse of matrix. If M is the matrix and M-1 is its inverse, M x M-1 gives
I (identity matrix).
int main(){
int a[3][3],i,j;
float determinant=0;
return 0;
}
Output:
The matrix is
3 5 2
1 5 8
3 9 2
Inverse of matrix is:
Initialize an array
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
ch ch[0] ch[1] ch[2] ch[3] ch[4]
a b c d e
Example: C program for reading no.of character and display the character
#include<stdio.h>
void main()
{
int i,n;
printf("Enter how many character of ");
scanf("%d",&n);
char ch[n];
printf("Enter %d character",n);
ch[0]='\0';
for(i=1;i<n;i++){
getchar();
ch[i]=getchar();
}
printf("Your entered character are");
for(i=0;i<=n;i++)
putchar(ch[i]);
Note:
When we assign a string to character array it store entire string of character into character
array variable and last index of that character array variable it store ‘\0’ character, to maintain
where the string is terminated.
char ch[]={‘I’,’N’,’D’,’I’,’A};
it store like: ch ch[0] ch[1] ch[2] ch[3] ch[4]
I N D I A
Basically the character array is used for accepting the string from user and store into one
variable.
Multi-Dimensional Arrays
C allows for arrays of two or more dimensions. A two-dimensional (2D) array is an array of
arrays. A three-dimensional (3D) array is an array of arrays of arrays.
In C programming an array can have two, three, or even ten or more dimensions. The maximum
dimensions a C program can have depends on which compiler is being used.
More dimensions in an array means more data be held, but also means greater difficulty in
managing and understanding arrays.
How to Declare a Multidimensional Array in C
A multidimensional array is declared using the following syntax:
type array_name[d1][d2][d3][d4]………[dn];
Where each d is a dimension, and dn is the size of final dimension.
Examples:
int table[5][5][20];
float arr[5][6][5][6][5];
In Example 1:
int designates the array type integer.
table is the name of our 3D array.
Our array can hold 500 integer-type elements. This number is reached by multiplying the
value of each dimension. In this case: 5x5x20=500.
In Example 2:
Array arr is a five-dimensional array.
It can hold 4500 floating-point elements (5x6x5x6x5=4500).
Can you see the power of declaring an array over variables? When it comes to holding multiple
values in C programming, we would need to declare several variables. But a single array can
hold thousands of values.
Like any other variable or array, a 3D array can be initialized at the time of compilation. By
default, in C, an uninitialized 3D array contains “garbage” values, not valid for the intended
use.
Let’s see a complete example on how to initialize a 3D array:
#include<stdio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=
{
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
In the code above we have declared a multidimensional integer array named “arr” which can
hold 3x3x3 (or 27) elements.
We have also initialized the multidimensional array with some integer values.