Module3 18cps23 SKC
Module3 18cps23 SKC
MODULE-3
ARRAYS
ONE-DIMENSIONAL ARRAY
TWO-DIMENSIONAL ARRAY
CHARACTER ARRAY AND STRINGS
SEARCHING ALGORITHMS
o LINEAR SEARCH
o BINARY SEARCH
SORTING ALGORITHMS
o BUBBLE SORT
o SELECTION SORT
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
MODULE-III
ARRAYS AND STRINGS
3.1 Arrays
An Array is a special and powerful data structure and it is used to store, process and print large
amounts of data.
“An array is a collection of similar type of items (elements) stored sequentially
(continuously) one after the other in memory”.
A[0] 10
A[1] 20
A[2] 30
A[3] 40
A[4] 50
The Elements in the Array A can be accessed using the common name A, but with different
index.
The Element ‘10’ is called 0th Element and it can be accessed using the Subscript 0 (called Index
‘0’) along with name of the array ‘A’.
B[0] ‘A’
B[1] ‘r’
B[2] ‘r’
B[3] ‘a’
B[4] ‘y’
3. float C[5]; //Array of 5 floats
C[0] 12.56
C[1] 234.20
C[2] 215.60
C[3] 322.50
C[4] 123.45
An ‘Index’ is also called as Subscript ([ ]). It is used to indicate the position of an element in
the Array.
An array is a fixed-size sequenced collection of elements of the same data type. It is simply a
grouping of like-typed data.
Basic Properties of the Arrays
1. All the elements in an array should be of the same data type.
Where,
data_type: data type can be int, float, char etc.
array_name: name of the array which is a valid C variable.
size: it is the number of elements in the array.
Complete declaration ends with Semicolon.
Ex: int Marks[5];
Declares Marks as an array consisting of 5 elements of integer data type.
Ex: int Marks[5];
1000 35 Marks[0]
data type array_name 1002 45 Marks[1]
1004 65 Marks[2]
1006 55 Marks[3]
char name[5]; 1008 75 Marks[4]
5 memory locations are reserved. sizeof(int) is 2 bytes, 2*5=10 bytes are reserved.
5 memory locations are reserved. sizeof(char) is 1 bytes 1*5=5 bytes are reserved.
Santosh K C, CSE Dept. BIET, DVG 3
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Initialization of Single dimensional arrays
Once an array is declared it must be initialized with some values using Initialization.
“Process of assigning the values to the individual elements of an array is called as
Initialization of an array”.
a[0] 10
a[1] 20
a[2] 30
a[3]
40
a[4]
50
2. int a[5] = {10, 20};
10 20 0 0 0
a[0] a[1] a[2] a[3] a[4]
When the numbers of initial values are lesser than declared array size then those many elements
will be initialized and other memory locations are automatically initialized to 0’s, in case of
numeric arrays.
It is ‘partial array initialization’.
A r r a y \0
a[0] a[1] a[2] a[3] a[4] a[5]
for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
The size used during declaration of the array is useful to reserve the specified memory locations.
The array ‘a’ is a 2-dimensional array with 2 rows and 4 columns. This declaration informs the
compiler to reserve 8 locations (2*4=8 locations, 2*8=16 bytes in total) continuously one after
the other.
data_type array_name[row_size][col_size]={
{a1,a2,-----,an},
{b1,b2,-----,bn},
……………...,
{z1,z2,-----,zn}
};
0 1 2
0 11 22 33
1
44 55 66
Rows 2
3 77 88 99
10 20 30
2. int a[4][3]= {
{11,22},
{33,4},
{55,66},
{77,88}
};
The array has 4 rows and 3 columns.
Columns
0 1 2
0 11 22 0
1 //This is a partial array initialization
33 44 0
Rows 2
3 55 66 0
77 88 0
To write/print the 2-dimensional array elements, we have to use two for loops along with
printf(), where the outer for loop indicates the number of rows to be printed and the inner for
loop indicates the number of columns to be printed.
Example Programs:
1. Write a C Program to read and print 2-dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n;
printf(“Enter the number of Rows and Columns of the Array:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the Array elements:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:
{ Enter the number of Rows and
scanf(“%d”,&a[i][j]); Columns of the Array:
2 2
}
Enter the Array elements:
} 1
printf(“Entered array elements are:\n”); 2
for(i=0;i<m;i++) 3
{ 4
for(j=0;j<n;j++) Entered array elements are:
{ 1 2
printf(“%d\t”,a[i][j]); 3 4
}
}
printf(“\n”);
}
}
3. Write a C program to find the largest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n,big=-1;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)
4. Write a C program to find the smallest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n,small=9999;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:
{ Enter the size of matrix:
2 2
scanf(“%d”,&a[i][j]);
Enter the elements of Matrix A:
} 10 20
} 30 40
for(i=0;i<m;i++) The largest element is: 10
{
for(j=0;j<n;j++)
{
if(a[i][j]<small)
{
small=a[i][j];
}
}
}
printf(“The smallest element is:%d\n”,small);
}
D A V A N G E R E \0 Null character
0 1 2 3 4 5 6 7 8 9
Where,
char: data type used to declare the strings or characters.
string_name: It specifies the name of the given string.
size: The size or maximum length (number of characters including ‘\0’) of the string is specified in
square brackets.
Length of the String: The ‘length’ is the number of characters stored in the string up to but not
including the null character.
Example
1. char name[21];
Size of the string is 21, means that it can store up to 20 characters plus one null character.
2. char str[10];
Size of the string is 10, means that it can store up to 10 characters plus one null character.
Examples:
1. char a[9]={‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’, ‘\0’};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized
with the characters in the order specified.
a C O M P U T E R \0
0 1 2 3 4 5 6 7 8
Santosh K C, CSE Dept. BIET, DVG 12
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
2. char b[10]={‘R’, ‘A’, ‘M’, ‘A’, ‘\0’};
The compiler allocates 10 memory locations ranging from 0 to 9 and these locations are
initialized with the characters in the order specified. The remaining locations are automatically
initialized to null-characters as shown below:
b R A M A \0 \0 \0 \0 \0 \0
0 1 2 3 4 5 6 7 8 9
3. char b[ ]={‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’, ‘\0’};
For this declaration, the compiler will set the array size to the total number of initial values. i.e.
9. The characters will be stored in these memory locations in the order specified as shown below:
b C O M P U T E R \0
0 1 2 3 4 5 6 7 8
4. char b[ ]= “COMPUTER”;
Here, the string length is 8 bytes. But string size is 9 bytes. So, the compiler reserves 8+1
memory locations and these locations are initialized with the characters in the order specified.
The string is terminated by ‘\0’ by the compiler.
b C O M P U T E R \0
0 1 2 3 4 5 6 7 8
Example C Program: Write a C program to read and display a string using scanf() and
printf().
#include<stdio.h>
void main()
{ Output:
char str[20]; Enter your name:
printf(“Enter your name:\n”); Bapuji
scanf(“%s”,str); Entered name is:
printf(“Entered name is:%s\n”,str); Bapuji
}
Syntax
length=strlen(str);
Where,
‘str’ is a string.
‘length’ is an integer representing the length of ‘str’ in bytes excluding the null character.
The ‘sizeof’ operator can be used to determine the size of a declared string.
Syntax
sizeof(str);
Where,
‘str’ is a string.
Example: Write a C program to find the length of string without using strlen() function.
#include<stdio.h>
#include<string.h>
void main()
{
char str[];
int length=0; Output:
printf(“Enter the string\n”); Enter the string
gets(str); Good morning
while(str[length]!=’\0’) Length of the string is=12
{
length ++;
}
printf(“Length of the string is=%d\n”, length);
}
Syntax strcpy(dest,src);
Where,
dest: it is the destination string
src: it is the source string.
The ‘strcpy()’ function copies the contents of source string src to destination string dest
including ‘\0’.
The strcpy() function copies characters from the source string to the destination string until it finds
null character.
Santosh K C, CSE Dept. BIET, DVG 16
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
s t r i n g \0
Destination
Syntax
strncpy(dest,src,n);
Where,
dest: it is the destination string.
src: it is the source string.
n: n is the number of characters to be copied into destination string.
src C o m p u t e r \0
0 1 2 3 4 5 6 7 8 9
dest C o m
0 1 2 3 4 5 6 7 8 9
Syntax
strcat(s1,s2);
Where,
s1: It is the first string
s2: It is the second string
The ‘strcat()’ function is used to concatenate or join the two strings.
The ‘strcat()’ function copies all the characters of string s2 to the end of string s1. The
NULL character of string s1 is replaced by the first character of s2.
M o r n i n g \0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
s1
G o o d M o r n i n g \0
0 1 2 3 4 5 6 7 8 9 10 12 13 14
Syntax strncat(s1,s2,n);
Where,
s1: It is the first string
s2: It is the second string
n: It is the number of characters of string s2 to be concatenated.
The ‘strncat()’ function is used to concatenate or join n characters of string s2 to the end of
string s1.
Santosh K C, CSE Dept. BIET, DVG 19
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Example: Write a C program to demonstrate the usage of strncat().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”;
strncat(str1,str2,4);
printf(“The concatenated String=%s”,str1);
}
Output: The concatenated String=GoodMorn.
s1
G o o d \0
0 1 2 3 4 5 6 7 8 9 10 12 13 14
s2
M o r n i n g \0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
s1
G o o d M o r n \0
0 1 2 3 4 5 6 7 8 9 10 12 13 14
Syntax
strcmp(s1,s2);
Where,
s1: It is the first string.
s2: It is the second string.
Example:
1.
s1 c a r \0
s2 c a t \0
strcmp(s1,s2);
“car” and “cat” are different strings. The characters ‘r’ and ‘t’ have different ASCII values. It
returns negative value since ASCII value of ‘r’ is less than the ASCII value of ‘t’.
2.
s1 c a r \0
s2 c a r \0
strcmp(s1,s2);
Since both the strings are same, the function returns 0.
3.
s1 c a t \0
s2 c a r \0
strcmp(s1,s2);
“cat” and “car” are different strings. The characters ‘t’ and ‘r’ have different ASCII values. It
returns positive value since ASCII value of ‘t’ is greater than the ASCII value of ‘r’.
Syntax strncmp(s1,s2,n);
Where,
s1: It is the first string.
s2: It is the second string.
n: It is the number of characters to be compared.
This function is used to compare first n number of characters in two strings.
The comparison starts with first character of each string. The comparison continues till the
corresponding characters differ or until the end of the character is reached or specified numbers of
characters have been tested.
The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
2. If s1 is greater than s2, a positive value is returned.
3. If s1 is less than s2, then the function returns a negative value.
Example: Write a C program to demonstrate the usage of strcmp().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[10]=”Hello”;
char s2[10]=”Hey”;
if(strcmp(s1,s2,2)==0)
printf(“The first two characters in the strings are identical”);
else
printf(“The first two characters in the strings are not identical”);
}
Example: C Program to search the ‘key’ element in an array using linear search algorithm.
#include <stdio.h>
void main()
{
int array[100], key, i, n;
2. Binary Search:
Binary search is a fast searching algorithm. This search algorithm works on the principle of divide
and conquers.
Binary search works on sorted arrays. Binary search begins by comparing the middle element of the
array with the target value. If the target value matches the middle element, its position in the array is
returned. If the target value is less than the middle element, the search continues in the lower half of
the array. If the target value is greater than the middle element, the search continues in the upper half
of the array.
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that
the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a
sorted array, so we also know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
We compare the value stored at location 5 with our target value. We find that it is a match.
Example: C Program to search key elements in array using binary search algorithms.
#include<stdio.h>
void main()
{
int n, i, arr[50], key, first, last, middle;
Output:
printf("Enter total number of elements :");
Enter number of
scanf("%d",&n);
elements in array:
printf("Enter array elements:\n");
5
for (i=0; i<n; i++)
Enter elements of array
{
10
scanf("%d",&arr[i]);
25
}
35
printf("Enter a number to find :");
50
scanf("%d", &key);
65
first = 0;
Enter a number to
last = n-1;
search:
while (first <= last)
65
{ middle = (first+last)/2;
65 is present at location 5
if ( arr[middle] == key)
{
printf("%d found at location %d\n", key, middle+1);
break;
}
else if ( arr[middle] < key)
{
first = middle + 1;
}
1. Selection sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based
algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted
part at the right end.
Initially, the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost element, and
that element becomes a part of the sorted array.
This process continues moving unsorted array boundary by one element to the right. This algorithm
is not suitable for large data sets.
How Selection Sort Works?
Consider the following depicted array as an example.
For the first position in the sorted list, the whole list is scanned sequentially. The first position where
14 is stored presently, we search the whole list and find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list,
appears in the first position of the sorted list.
We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array. Following is a pictorial depiction of
the entire sorting process –
2. Bubble Sort.
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
Bubble sort algorithm starts by comparing the first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first
element is greater than second then, you need to swap the elements but, if the first element is
smaller than second, you mustn't swap the element.
Then, again second and third elements are compared and swapped if it is necessary and this
process go on until last and second last element is compared and swapped. This completes the
first step of bubble sort.
If there are n elements to be sorted then, the process mentioned above should be repeated n-
1 times to get required result. But, for better performance, in second step, last and second last
elements are not compared because; the proper element is automatically placed at last after first
step. Similarly, in third step, last and second last and second last and third last elements are not
compared and so on.
Example: C Program to sort the given array elements using Bubble sort Algorithm.
#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n); Output:
printf("Enter the array elements: "); Enter the size of array:
for(i=0;i<n;++i) 5
scanf("%d",&a[i]); Enter elements of array
for(i=1;i<n;++i) 30
for(j=0;j<(n-i);++j) 25
35
if(a[j]>a[j+1])
10
{ 56
temp=a[j]; Sorted elements:
a[j]=a[j+1]; 10
a[j+1]=temp; 25
} 30
35
printf("\nArray after sorting: ");
56
for(i=0;i<n;++i)
printf("%d ",a[i]);
}
ASSIGNMENT QUESTIONS