UNIT2 array
UNIT2 array
UNIT2 array
Contents
Single and Multidimensional Arrays: Array Declaration and Initialization of arrays – Arrays as
function arguments. Strings: Initialization and String handling functions.
ARRAYS
Introduction:
So far we have used only single variable name for storing one data item. If we need to store
multiple copies of the same data then it is very difficult for the user. To overcome the difficulty a
new data structure is used called arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored
contiguously in the memory under one variable name.
An array can be declared of any standard or custom data type.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100
variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C
programming arrays is introduced in C which gives the capability to store the 100 roll numbers in
the contiguous memory which has 100 blocks and which can be accessed by single variable
name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays
Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non-
contiguous allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address from
base register and then it will refer relative address of memory location with respect to base
address.
How to allocate contiguous memory?
1. Using static array declaration.
2. Using alloc ( ) / malloc ( ) function to allocate big chunk of memory dynamically.
Array Terminologies:
Size: Number of elements or capacity to store elements in an array. It is always mentioned in
square brackets [ ].
Type: Refers to data type. It decides which type of element is stored in the array. It is also
instructing the compiler to reserve memory according to the data type.
Base: The address of the first element is a base address. The array name itself stores address
of the first element.
Index: The array name is used to refer to the array element. For example num[x], num is array
and x is index. The value of x begins from 0.The index value is always an integer value.
Range: Value of index of an array varies from lower bound to upper bound. For example in
num[100] the range of index is 0 to 99.
Word: It indicates the space required for an element. In each memory location, computer can
store a data piece. The space occupation varies from machine to machine. If the size of element
is more than word (one byte) then it occupies two successive memory locations. The variables of
data type int, float, long need more than one byte in memory.
Characteristics of an array:
1. The declaration int a [5] is nothing but creation of five variables of integer types in
memory instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one
another with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the
other elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or
array variable of its type.
6. Array elements are stored in contiguous memory locations.
Array Declaration:
Array has to be declared before using it in C Program. Array is nothing but the collection of
elements of similar data types.
Syntax: <data type> array name [size1][size2]..... [sizen];
Types of Array
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array
Here we are learning the different ways of compile time initialization of an array.
Ways of Array Initializing 1-D Array:
1. Size is Specified Directly
2. Size is Specified Indirectly
Method 1: Array Size Specified Directly
In this method, we try to specify the Array Size directly.
int num [5] = {2,8,7,6,0};
In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.
num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;
As at the time of compilation all the elements are at specified position So This initialization
scheme is Called as “Compile Time Initialization“.
Graphical Representation:
Accessing Array
1. We all know that array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair of
square brackets [ ].
Consider the below example of an array
So whenever we tried accessing array using arr[i] then it returns an element at the location*(arr
+ i)
Accessing array a[i] means retrieving element from address (a + i).
Example Program2: Accessing array
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
}
getch();
}
Output:
51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
5 5 5 5
26 26 26 26
Operations with One Dimensional Array
1. Deletion – Involves deleting specified elements form an array.
2. Insertion – Used to insert an element at a specified position in an array.
3. Searching – An array element can be searched. The process of seeking specific
elements in an array is called searching.
4. Merging – The elements of two arrays are merged into a single one.
5. Sorting – Arranging elements in a specific order either in ascending or in descending
order.
Example Programs:
1. C Program for deletion of an element from the specified location
from an Array
#include<stdio.h>
int main() {
int arr[30], num, i, loc;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Read elements in an array
printf("\nEnter %d elements :", num);
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
//Read the location
printf("\nLocation of the element to be deleted :");
scanf("%d", &loc);
/* loop for the deletion */
while (loc < num) {
arr[loc - 1] = arr[loc];
loc++; }
num--; // No of elements reduced by 1
//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter 5 elements: 3 4 1 7 8
Location of the element to be deleted: 3
3 4 7 8
2. C Program to delete duplicate elements from an array
int main() {
int arr[20], i, j, k, size;
printf("\nEnter array size: ");
scanf("%d", &size);
printf("\nAccept Numbers: ");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("\nArray with Unique list: ");
for (i = 0; i < size; i++) {
for (j = i + 1; j < size;) {
if (arr[j] == arr[i]) {
for (k = j; k < size; k++) {
arr[k] = arr[k + 1]; }
size--; }
else
j++; }
}
for (i = 0; i < size; i++) {
printf("%d ", arr[i]); }
return (0);
}
Output:
Enter array size: 5
Accept Numbers: 1 3 4 5 3
Array with Unique list: 1 3 4 5
3. C Program to insert an element in an array
#include<stdio.h>
int main() {
int arr[30], element, num, i, location;
printf("\nEnter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
printf("\nEnter the element to be inserted:");
scanf("%d", &element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location
for (i = num; i >= location; i--) {
arr[i] = arr[i - 1]; }
num++;
arr[location - 1] = element;
//Print out the result of insertion
for (i = 0; i < num; i++)
printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
1 2 3 4 5
Enter the element to be inserted: 6
Enter the location: 2
1 6 2 3 4 5
4. C Program to search an element in an array
#include<stdio.h>
int main() {
int a[30], ele, num, i;
printf("\nEnter no of elements:");
scanf("%d", &num);
printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &a[i]); }
//Read the element to be searched
printf("\nEnter the elements to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
while (i < num && ele != a[i]) {
i++; }
//If i < num then Match found
if (i < num) {
printf("Number found at the location = %d", i + 1);
}
else {
printf("Number not found"); }
return (0);
}
Output:
Enter no of elements: 5
11 22 33 44 55
Enter the elements to be searched: 44
Number found at the location = 4
5. C Program to copy all elements of an array into another array
#include<stdio.h>
int main() {
int arr1[30], arr2[30], i, num;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Accepting values into Array
printf("\nEnter the values:");
for (i = 0; i < num; i++) {
scanf("%d", &arr1[i]); }
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++) {
arr2[i] = arr1[i]; }
//Printing of all elements of array
printf("The copied array is:");
for (i = 0; i < num; i++)
printf("\narr2[%d] = %d", i, arr2[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter the values: 11 22 33 44 55
The copied array is: 11 22 33 44 55
6. C program to merge two arrays in C Programming
#include<stdio.h>
int main() {
int arr1[30], arr2[30], res[60];
int i, j, k, n1, n2;
printf("\nEnter no of elements in 1st array:");
scanf("%d", &n1);
for (i = 0; i < n1; i++) {
scanf("%d", &arr1[i]); }
printf("\nEnter no of elements in 2nd array:");
scanf("%d", &n2);
for (i = 0; i < n2; i++) {
scanf("%d", &arr2[i]); }
i = 0;
j = 0;
k = 0;
// Merging starts
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
res[k] = arr1[i];
i++;
k++; }
else {
res[k] = arr2[j];
k++;
j++; }
}
/*Some elements in array 'arr1' are still remaining where as the array
'arr2' is exhausted*/
while (i < n1) {
res[k] = arr1[i];
i++;
k++; }
/*Some elements in array 'arr2' are still remaining where as the array
'arr1' is exhausted */
while (j < n2) {
res[k] = arr2[j];
k++;
j++; }
//Displaying elements of array 'res'
printf("\nMerged array is:");
for (i = 0; i < n1 + n2; i++)
printf("%d ", res[i]);
return (0);
}
Enter no of elements in 1st array: 4
11 22 33 44
Enter no of elements in 2nd array: 3
10 40 80
Merged array is: 10 11 22 33 40 44 80
1 integer roll 1 10
Declaration a[3][4]
No of Rows 3
No of Columns 4
No of Cells 12
Memory Representation:
1. 2-D arrays are stored in contiguous memory location row wise.
2. 3 X 3 Array is shown below in the first Diagram.
3. Consider 3×3 Array is stored in Contiguous memory location which starts from 4000.
4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next
memory location i.e. Elements stored row-wise
5. After Elements of First Row are stored in appropriate memory locations, elements of
next row get their corresponding memory locations.
6. This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation:
a[0][1] = a[0][0] + Size of Data Type
a[0][0] 4000
a[0][1] 4002
a[0][2] 4004
a[1][0] 4006
a[1][1] 4008
a[1][2] 4010
a[2][0] 4012
a[2][1] 4014
a[2][2] 4016
Initializing 2D Array
Limitations of Arrays:
Array is very useful which stores multiple data under single name with same data type.
Following are some listed limitations of Array in C Programming.
A. Static Data
1. Array is Static data Structure
2. Memory Allocated during Compile time.
3. Once Memory is allocated at Compile Time it cannot be changed during Run-time
Applications of Arrays:
Array is used for different verities of applications. Array is used to store the data or values of
same data type. Below are the some of the applications of array –
A. Stores Elements of Same Data Type
Array is used to store the number of elements belonging to same data type.
int arr[30];
Above array is used to store the integer numbers in an array.
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Similarly if we declare the character array then it can hold only character. So in short character
array can store character variables while floating array stores only floating numbers.
B. Array Used for maintaining multiple variable names using single name
Suppose we need to store 5 roll numbers of students then without declaration of array we need
to declare following –
int roll1, roll2, roll3, roll4, roll5;
1. Now in order to get roll number of first student we need to access roll1.
2. Guess if we need to store roll numbers of 100 students then what will be the procedure.
3. Maintaining all the variables and remembering all these things is very difficult.
Consider the Array int roll[5]; Here we are using array which can store multiple values and we
have to remember just single variable name.
C. Array can be used for Sorting Elements
We can store elements to be sorted in an array and then by using different sorting technique we
can sort the elements.
Different Sorting Techniques are:
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Bucket Sort
D. Array can perform Matrix Operation
Matrix operations can be performed using the array. We can use 2-D array to store the matrix.
Matrix can be multi dimensional.
E. Array can be used in CPU Scheduling
CPU Scheduling is generally managed by Queue. Queue can be managed and implemented
using the array. Array may be allocated dynamically i.e at run time. [Animation will Explain more
about Round Robin Scheduling Algorithm | Video Animation]
F. Array can be used in Recursive Function
When the function calls another function or the same function again then the current values are
stores onto the stack and those values will be retrieving when control comes back. This is similar
operation like stack.
STRINGS
A string is a sequence of character enclosed with in double quotes (“ ”) but ends with
\0. The compiler puts \0 at the end of string to specify the end of the string.
To get a value of string variable we can use the two different types of formats.
Using scanf() function as: scanf(“%s”, string variable);
C library supports a large number of string handling functions. Those functions are stored under
the header file string.h in the program.
Syntax
strcat (StringVariable1, StringVariable 2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
printf(‚ Concatenation String is:%s‛, strcat(str1,str2));
getch();
}
Output:
Enter First String
Good
Enter Second String
Morning
Concatenation String is: GoodMorning
(iii) strcmp() function
strcmp() function is used to compare two strings. strcmp() function does a case sensitive
comparison between two strings. The two strings are compared character by character until there
is a mismatch or end of one of the strings is reached (whichever occurs first). If the two strings
are identical, strcmp( ) returns a value zero. If they‟re not, it returns the numeric difference
between the ASCII values of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmp(str1,str2);
printf(‚ Compare String Result is:%d‛,res);
getch();
}
Output:
Enter First String
Good
Enter Second String
Good
Compare String Result is: 0
strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.
Syntax
strcmpi(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmpi(str1,str2);
printf(‚ Compare String Result is:%d‛,res);
getch();
}
Output:
Enter First String
WELCOME
Enter Second String
welcome
Compare String Result is: 0
(v) strcpy() function:
strcpy() function is used to copy one string to another. strcpy() function copy the contents of
second string to first string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
strcpy(str1,str2)
printf(‚ First String is:%s‛,str1);
printf(‚ Second String is:%s‛,str2);
getch();
}
Output:
Enter First String
Hello
Enter Second String
welcome
First String is: welcome
Second String is: welcome
(vi) strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Lowercase String : %s‛, strlwr(str));
getch();
}
Output:
Enter String
WELCOME
Lowercase String : welcome
(vii) strrev() function:
strrev() function is used to reverse characters in a given string.
Syntax
strrev(StringVariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Reverse String : %s‛, strrev(str));
getch();
}
Output:
Enter String
WELCOME
Reverse String : emoclew
(viii) strupr() function:
strupr() function is used to convert all characters in a given string from lower case to
uppercase letter.
Syntax
strupr(Stringvariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Uppercase String : %s‛, strupr(str));
getch();
}
Output:
Enter String
welcome
Uppercase String : WELCOME