Chapter 7.1
Chapter 7.1
Chapter 7.1
Array is a derived data type in 'C' that store same/similar type of elements. That is it is a fixed
size sequenced collection of elements of same data type. (Here sequenced collection means
contiguous memory). Arrays can be of any type supported by C , including constructed data type
(structure, union, enum). The use of arrays allows for the development of smallest and more
readable programs. Simply we can define array as a finite ordered set of homogenous elements.
Why it is necessary?
If we have to store information of 100 students.
100 students.
Without array : we use
int sr1; int sr2; int sr3; .........................; int sr100; (Inefficient Task)
With array : We use
int sr[100]; can store 100 students information. (Efficient Task)
sr[0],sr[1],...................................,sr[99] , here 0-99 are index.
Types of Arrays
There are two types of arrays. These are one-dimensional and multi-dimensional arrays. In this
text, we will study only one-dimensional and two-dimensional arrays in details.
One-dimensional arrays
It is a list of items with one variable name using only one subscript.
int ar[5]; where 5 is array size i.e. no of elements.
There is a variable with name 'ar' that can store 5 integer values.
Declaration : General form
data-type array-name [size];
example : float f1[100]; (0-99) index 0 to n-1
int i1[10]; (0-9) index 0 to n-1
char name[10]; (0-9) index 0 to n-1, Only 10 characters can be stored.
We have
WELL DONE
1. Compile-time initialization
Example:
Global initialization
int ar[5]={2,5,4,3,6};
void main()
{
.....................
}
Local initialization
void main()
{
float marks[5]={ 32.6 , 66.5 , 78.5 , 55.9 , 76.4 };
............................................
}
1. Starting with the first element(index = 0), compare the current element with the next
element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat
Step 1.
So as we can see in the representation above, after the first iteration, 6 is placed at the last index,
which is the correct position for it.
Similarly after the second iteration, 5 will be at the second last index, and so on.
Program
#include<stdio.h>
#include<conio.h>
Insertion Sort : Consider you have 10 cards out of a deck of cards in your hand. And they are
sorted, or arranged in the ascending order of their numbers.
If I give you another card, and ask you to insert the card in just the right position, so that the
cards in your hand are still sorted. What will you do?
Well, you will have to go through each card from the starting or the back and find the right
position for the new card, comparing it's value with each card. Once you find the right position,
you will insert the card there.
Similarly, if more new cards are provided to you, you can easily repeat the same process and
insert the new cards and keep the cards sorted too.
This is exactly how insertion sort works. It starts from the index 1(not 0), and each index
starting from index 1 is like a new card, that you have to place at the right position in the sorted
subarray on the left.
Following are some of the important characteristics of Insertion Sort:
1. It is efficient for smaller data sets, but very inefficient for larger lists.
2. Insertion Sort is adaptive, that means it reduces its total number of steps if a partially
sorted array is provided as input, making it efficient.
3. It is better than Selection Sort and Bubble Sort algorithms.
4. Its space complexity is less. Like bubble Sort, insertion sort also requires a single
additional memory space.
5. It is a stable sorting technique, as it does not change the relative order of elements which
are equal.
3. Then, we make the third element of the array as key and will compare it with elements to
it's left and insert it at the right position.
To insert new element in array, shift elements from the given insert position to one
position right. Hence, run a loop in descending order from size 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 ar[i] = ar[i - 1];.
Finally, after performing shift operation. Copy the new element at its specified position
i.e. ar[pos-1]=num;.
1. Input size and elements in array. Store it in some variable say size and arr.
2. Find frequency of each element and store it in an array say freq.
3. Print array elements with frequency 1 which is our required unique elements.
Program
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int ar[MAX_SIZE], freq[MAX_SIZE];
int size, i, j, count;
printf("Enter size of array : ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d",&ar[i]);
freq[i] = -1;
}
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
if(ar[i] == ar[j])
{
count++;
freq[j] = 0;
}
}
if(freq[i]! = 0)
{
freq[i] = count;
}
}
printf("\nUnique elements in the array are : ");
for(i=0; i<size; i++)
{
if(freq[i] == 1)
{
printf("%d", ar[i]);
}
}getch();return 0}
void main()
{
int arr1[100], fr1[100];
int n, i, j, ctr;
printf("\n\nCount frequency of each element of an array:\n");
printf("------------------------------------------------\n");
printf("Input the number of elements to be stored in the 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]);
fr1[i] = -1;
}
for(i=0; i<n; i++)
{
ctr = 1;
for(j=i+1; j<n; j++)
{
if(arr1[i]==arr1[j])
{
ctr++;
Declaration
Two-dimensional array can be declared as:
Global declaration
char string[50][30];
void main()
{
.............................
}
Local declaration
void main()
{
int ar[3][3];
..................
}
Initialization
example:
int ar[2][3]={{1, 2, 3},{5, 7, 8}};
Columns
Rows 0 1 2
}
else
{
printf("Array size mismatched.");
}
getch();
return 0;
}
Array multiplication
#include<stdio.h>
#include<conio.h>
void multi2darray(int [][10], int [][10], int [][10], int, int, int);
int main()
{
int i, j, A[10][10], B[10][10], r1, c1, r2, c2, C[10][10], k;
printf("Enter the maximum size of row and column of array A:");
scanf("%d%d", &r1, &c1);
if(c1==r2)
{
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("Enter A[%d][%d]:", i, j);
scanf("%d", &A[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("Enter B[%d][%d]", i, j);
scanf("%d",&B[i][j]);
}
}
multi2darray(A, B, C, r1, c1, c2);
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d", C[i][j]);
}
Multidimensional arrays
Two or more dimensional arrays are in this category. C allows arrays of three or more
dimensions. The exact limit depends on the compiler. We can check it by compiling a simple
program having a multidimensional array by our compiler and decide up to which dimension
does our compiler support. The general form of a multidimensional array declaration is
The valid range of values for the example above is 0 through 9. The first element of the array is
accessed using index value 0 and the last element of the array is accessed using index value 9.
An overflow error occurs when one attempts to access the example array using an index value
greater than 9. An underflow error occurs when one attempts to access the example array using
an index value less than 0. Either of these errors results in accessing memory not allocated to the
array. The result of accessing memory outside the memory allocated to the array is undefined in
many languages. Neither C nor C++ provide the ability to check for either error when an array is
passed to a function through a function parameter. Some languages such as Ada, Java, and Pascal
check the index values and prohibit use of index values which would reference memory outside
the memory allocated to the array. If the invalid array access can be detected at compile time a
compilation error is generated. If the invalid array access happens during run-time a run-time
exception is raised in Ada or Java.
Q. What is string? WAP to read 3x3 square matrix, find minimum integer value of a matrix,
replace the diagonal elements by the minimum element and display it records of 10 colleges.
[2072 chaitra]
Q. Explain with an example for compiler time initialization of 2D array. Describe how compiler
manages according to the number of initializers and size of an array given by a user in case of
1D array. [2072 Kartik]
There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4]={
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
int disp[2][4] = {10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, I recommend you to use the first method as it is
more readable, because you can visualize the rows and columns of 2d array in this method.
Things that you must consider while initializing a 2D array
We already know, when we initialize a normal array (or you can say one dimensional array)
during declaration, we need not to specify the size of it. However that’s not the case with 2D
However the actual representation of this array in memory would be something like this:
Q. Write down the significance of array in C. WAP to multiply two 3x3 matrix. Two matrix are
input from main() function and pass to a user defined function with argument with array. The
result is also displayed from main() function.
Q. Briefly explain array of pointers. How are array and pointer related? Give example. [2070]
Q. How are one dimensional and two dimensional arrays created in C? Explain with examples.
Q. WAP to read two matrices from user, add them and display the result in matrix form. [2070]
Q. How can we pass two dimensional arrays from one function to another? Explain with
example.
Q. WAP to find the second largest number in an array of n numbers. Read the value of n and the
elements of the array from the user. [2069]
Q. Can we pass whole array element from the function? WAP to pass an array to function and
sort them.