CP Unit V
CP Unit V
CP Unit V
5.0 Introduction
The fundamental data types, namely char, int, float, and double are used to store only one
value at any given time. Hence these fundamental data types can handle limited amounts of data.
In some cases we need to handle large volume of data in terms of reading, processing and
printing. To process such large amounts of data, we need a powerful data type that would
facilitate efficient storing, accessing and manipulation of data items. C supports a derived data
type known as array that can be used for such applications.
Arrays
An array is a fixed size sequenced collection of elements of the same data type.
It is simply grouping of like type data such as list of numbers, list of names etc.
Types of Arrays
We can use arrays to represent not only simple lists of values but also tables of data in two or
three or more dimensions.
1. One – dimensional arrays(1-D)
2. Two – dimensional arrays (2-D)
3. Multidimensional arrays (n-D)
5.1 Array
An array is collection of homogeneous elements that are represented under a single variable
name.
(Or)
An array is collection of same data type elements in a single entity.
It allocates sequential memory locations.
Individual values are called as elements.
The data type specifies the type of element that will be contained in the array, such as int, float, or
char or any valid data type.
The array name specifies the name of the array.
The size indicates the maximum number of elements that can be stored inside the array.
The size of array should be a constant value.
For example
int marks[10]; //integer array
1
UNIT-V COMPUTER PROGRAMMING
in marks[0], second element in marks[1], and so on. Therefore, the last element, that is the 10th
element, will be stored in marks[9].
C array indices start from 0. So for an array with N elements, the index that last element is N-1
Valid Statements
a = marks[0] + 10;
marks[4] = marks[0] + marks[2];
marks[2] = x[5] + y[10];
value[6] = marks[i] * 3;
Example 1: A C program that prints bytes reserved for various types of data and space required
for storing them in memory using array.
#include<stdio.h>
int main()
{
char c[10];
int i[10];
float f[10];
double d[10];
printf("\nThe type char requires %d byte",sizeof(char));
printf("\nThe type int requires %d bytes",sizeof(int)); printf("\
nThe type float requires %d bytes",sizeof(float)); printf("\nThe
type double requires %d bytes",sizeof(double));
printf("\n%d memory locations are reserved for 10 character elements", sizeof(c));
printf("\n%d memory locations are reserved for 10 integer elements", sizeof(i));
printf("\n%d memory locations are reserved for 10 float elements", sizeof(f));
printf("\n%d memory locations are reserved for 10 double elements", sizeof(d));
return 0;
}
Output
The type char requires 1 byte
The type int requires 2 bytes
The type float requires 4 bytes
The type double requires 8 bytes
10 memory locations are reserved for 10 character elements
20 memory locations are reserved for 10 integer elements
2
UNIT-V COMPUTER PROGRAMMING
40 memory locations are reserved for 10 float elements
80 memory locations are reserved for 10 double elements
For example
int i ,marks[10];
for (i=0; i<10; i++)
printf(“%d”,marks[i]);
For example
int marks[5]={90,87,76,69,82};
While initializing the array at the time of declaration, the programmer may omit the size of the
array. For example,
int marks[]= {98, 97, 90};
3
UNIT-V COMPUTER PROGRAMMING
Input values from keyboard
An array can be filled by inputting values from the keyboard. In this method, a while or for loop
is executed to input the value for each element of the array. For example:
int i ,marks[10];
for (i=0; i<10; i++)
scanf(“%d”,&marks[i]);
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5
Example 3: Write a C Program to print the maximum and minimum element in the array.
#include <stdio.h>
int main()
{
int i, n, a[20], max, min;
printf("Enter the number of elements in the array :
"); scanf("%d", &n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
4
UNIT-V COMPUTER PROGRAMMING
printf("a[%d] = ",i);
scanf("%d",&a[i]);
}
max = min = a[0];
for(i=1;i<n;i++)
{
if(a[i]<min)
min = a[i];
if(a[i]>max)
max = a[i];
}
printf("\n The smallest element is : %d\n", min);
printf("\n The largest element is : %d\n", max);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The smallest element is : 1
The largest element is : 5
Linear Search
Linear search, also called as sequential search, is a very simple method used for searching
an array for a particular value. It works by comparing the value to be searched with every
element of the array one by one in a sequence until a match is found. It is mostly used to search
an unordered list of elements. For example, if an array a[] is declared and initialized as,
int a[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is
present in the array or not. If yes, then it returns the position of its occurrence. Here, POS = 3
(index starting from 0).
Example 4: Write a C Program to search an element in an array using the linear search
technique.
#include <stdio.h>
int main()
{
int a[100],n,i,key,flag=0;
printf("Enter number of elements:");
scanf("%d", &n);
5
UNIT-V COMPUTER PROGRAMMING
printf("Enter elements\n");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
printf("Enter an element to be searched:");
scanf("%d", &key);
/* linear search starts here */
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf("%d is found at position %d\n", key, i);
flag=1;
break;
}
}
if(flag==0)
printf("%d is not found\n",key);
return 0;
}
Output
Enter number of elements: 5
Enter elements
Enter a[0] = 14
Enter a[1] = 5
Enter a[2] = 23
Enter a[3] = 9
Enter a[4] = 15
Enter an element to be searched: 9
9 is found at position 3
Binary Search
Binary search is a searching algorithm that works efficiently with a sorted list.
6
UNIT-V COMPUTER PROGRAMMING
scanf("%d", &key);
low = 0, high = n-1;
while(high>=low)
{
mid = (low + high)/2;
if (a[mid] == key)
{
printf("\n %d is found at position %d", key, mid);
flag = 1;
break;
}
else if (a[mid]>key)
high = mid-1;
else
low = mid+1;
}
if (flag == 0)
printf("\n %d does not found in the array",
key); return 0;
}
Output
Enter the number of elements in the array: 5
Enter the elements
Enter a[0] = 11
Enter a[1] = 26
Enter a[2] = 32
Enter a[3] = 49
Enter a[4] = 68
Enter the element to be searched: 49
49 is found at position 3
5.3 Sorting
Sorting means arranging the elements of an array in specific order may be either ascending or
descending. There are different types of sorting techniques are available:
1. Bubble sort
2. Selection sort
3. Insert sort
4. Merge sort
5. Quick sort etc.
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly
steps through the list to be sorted, compares each pair of adjacent items and swaps them if they
are in the wrong order.
7
UNIT-V COMPUTER PROGRAMMING
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
/* bubble sort logic starts from here */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
if(a[i]>a[j]) //> for ascending order, < for descending order
{
temp=a[i]; Output
a[i] = a[j]; Enter number of elements: 5
a[j] = temp; Enter elements
} Enter a[0] = 14
} Enter a[1] = 5
printf("Sorted elements ....\n"); Enter a[2] = 23
for(i=0;i<n;i++) Enter a[3] = 9
printf("%3d",a[i]); Enter a[4] = 15
printf("\n"); Sorted elements ....
return 0; 5 9 14 15 23
}
Selection sort is a simple sorting algorithm. This sorting algorithm is in-place comparison based
algorithm in which the list is divided into two parts, sorted part at left end and unsorted part at
right end. Initially sorted part is empty and unsorted part is entire list.
8
UNIT-V COMPUTER PROGRAMMING
a[i] = a[min];
a[min] = temp;
}
printf("Sorted elements ....\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
return 0;
}
In mathematics, we represent a particular value in a matrix by using two subscripts such as Vij.
th
Here V denotes the entire matrix, Vij refers to the value in i row and j column.
th
In the above table V23 refers to the value “80”. C allows us to define such tables of items by
using two-dimensional arrays.
Definition
A list of items can be represented with one variable name using two subscripts and such
a variable is called a two – subscripted variable or a two – dimensional (2D) array.
9
UNIT-V COMPUTER PROGRAMMING
5.4.2 Initializing Two- Dimensional Arrays
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in curly braces.
int table[2] [3] = {0,0,0,1,1,1};
This initializes the elements of first row to zero and the second row to one.
This initialization can also be done row by row. The above statement can be equivalently written as
The first element of each row is explicitly initialized to zero while the other elements are
automatically initialized to zero.
The following statement will also achieve the same result
int m[3][5] = { 0 };
11
UNIT-V COMPUTER PROGRAMMING
/* Display A and B matrices */
printf("The Matrix A\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%3d",a[i][j]);
printf("\n");
}
printf("The Matrix B\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%3d",b[i][j]);
printf("\n");
}
/*Add two matrices and print resultant matrix */
printf("The resultant matrix is\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
c[i][j]=a[i][j]+b[i][j]; // for subtract, use minus (-) instead of plus (+) sign
printf("%3d",c[i][j]);
}
printf("\n");
}
return 0;
}
Output
Enter number of rows and columns (between 1 and 10): 3 3
Enter elements of first matrix: 1 2 3 4 5 6 7 8 9
Enter elements of second matrix: 1 2 3 4 5 6 7 8 9
The matrix A
123
456
789
The matrix B
123
456
789
The resultant matrix is
2 4 6
8 10 12
14 16 18
12
UNIT-V COMPUTER PROGRAMMING
int m,n,p,q,i,j,k;
printf("Enter number of rows and columns of first matrix(between 1 and
10):"); scanf("%d%d",&m,&n);
printf("Enter number of rows and columns of second matrix(between 1 and 10):");
scanf("%d%d",&p,&q);
if(n==p)
{
/* Read the elements of first matrix */
printf("Enter elements of first matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
/* Read the elements of second matrix */
Print f("Enter elements of second matrix\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
}
/* Display A and B matrices */
printf("The Matrix A\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%3d",a[i][j]);
printf("\n");
}
printf("The Matrix B\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%3d",b[i][j]);
printf("\n");
}
/*multiply two matrices and print resultant matrix */
printf("The resultant matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0; /* Initializing resultant matrix elements to zero */
for(k=0;k<p;k++)
c[i][j] += a[i][k]*b[k][j];
printf("%3d",c[i][j]);
}
printf("\n");
}
}
else
13
UNIT-V COMPUTER PROGRAMMING
printf("Multiplication is not possible\n");
return 0;
}
Output
Enter number of rows and columns of first matrix (between 1 and 10):2 3
Enter number of rows and columns of second matrix (between 1 and 10):3 2
Enter elements of first matrix: 1 2 3 4 5 6
Enter elements of second matrix: 1 2 3 4 5 6
The Matrix A
1 2 3
4 5 6
The Matrix B
1 2
3 4
5 6
The resultant matrix is
22 28
49 64
Initializing 3D Array
Like the one-dimensional arrays, three-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
This initializes the elements of first two dimensional (matrix) first row to zero’s and the second
row to one’s and second matrix elements are first row to six’s and the second row to seven’s.
This initialization is done row by row.
The above statement can be equivalently written as
char string1[30];
char str2[7] = “String”;
The following declaration creates string named “str2” and initialized with value “String”. To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word.
Note: The C compiler automatically places the '\0' at the end of the string when it initializes the
array.
The terminating null (‘\0’) is important, because it is the only way the functions that work with
a string can know where the string ends.
15
UNIT-V COMPUTER PROGRAMMING
5.7 Standard Library String Functions
With every C compiler a large set of useful string handling library functions are provided.
For using these functions, we need to include the header file string.h
Function Use
strlen() Finds length of a string
strlwr() Converts a string to lowercase
strupr() Converts a string to uppercase
strcat() Appends one string at the end of another
strcpy() Copies a string into another
strcmp() Compares two strings
strchr() Finds first occurrence of a given character in a string
strstr() Finds first occurrence of a given string in another string
strrev() Reverses the given string
strlen() function
This function counts the number of characters present in a string. Syntax for strlen() function
is given below:
size_t strlen(const char *str);
The function takes a single argument, i.e, the string variable whose length is to be found,
and returns the length of the string passed.
strcpy( ) function
This function copies the contents of one string into another. Syntax for strcpy() function is given
below.
char * strcpy ( char * destination, const char * source );
Example
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
16
UNIT-V COMPUTER PROGRAMMING
If destination string length is less than source string, entire source string value won’t be copied into
destination string.
For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and remaining 10
characters won’t be copied and will be truncated.
Output
Source string = Sayonara
Destinnation string = Sayonara
strcat( ) function
It combines two strings. It concatenates the source string at the end of the destination string.
Syntax for strcat( ) function is given below.
For example, “Bombay” and “Nagpur” on concatenation would result a new string
“BombayNagpur”.
strcmp( ) function
It compares two strings to find out whether they are same or different. 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.
17
UNIT-V COMPUTER PROGRAMMING
If the two strings are identical, strcmp( ) returns a value zero. If they’re not identical, it
returns the numeric difference between the ASCII values of the first non-matching pairs of
characters.
Syntax for strcmp( ) function is given below.
Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example 15: C program that illustrates the usage of strcmp() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = Output
"Ferry" ; int i, j, k ; 0 4 -32
i = strcmp ( string1, "Jerry" ) ; j
= strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry
boy" ) ; printf ( "\n%d %d %d", i,
j, k ) ;
}
18
UNIT-V COMPUTER PROGRAMMING
The putchar() function prints the character passed to it on the screen and returns the
same character. This function puts only single character at a time. In case you want to display
more than one characters, use putchar() method in the loop. #include <stdio.h>
int main( )
{
int ch;
printf("Enter a character:");
ch=getchar();
putchar(ch);
return 0;
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.
The puts() function writes the string s and a trailing newline to stdout.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string:");
gets( str );
puts("Hello!");
puts(str);
return 0;
}
Output
Enter a string: prasad Ch
Hello! prasad Ch
19