New UNIT-III
New UNIT-III
An Array is a collection of similar data elements. These data elements have the same data
type. The elements of the array are stored in consecutive memory locations and are referenced by
an index (also known as subscript). Subscript indicates an ordinal number of the elements
counted from the beginning of the array.
Definition:
An array is a data structure that is used to store data of the same type. The position of an element
is specified with an integer value known as index or subscript.
E.g.
1 3 5 2 a(integer array)
Characteristics:
i) All the elements of an array share a common name called as array name
ii) The individual elements of an array are referred based on their position.
2. Multi-dimensional array
Declarations of Arrays
Array has to be declared before using it in C Program. Declaring Array means specifying three
things.
type name[size]
Here the type can be either int, float, double, char or any oher valid data type. The number within
the brackets indicates the size of the array, i.e., the maximum number of elements that can be
stored in the array.
Elements of the array can also be initialized at the time of declaration as in the case of
every other variable. When an array is initialized, we need to provide a value for every element
in the array. Arrays are initialized by writing,
The values are written with curly brackets and every value is separated by a comma. It is a
compiler error to specify more number of values than the number of elements in the array.
1 3 5 2
a
[0] [1] [2] [3] subscripts or indices
b) If the number of initializers in the list is less than array size, the leading array locations gets
initialized with the given values. The rest of the array locations getsinitialized to
0 - for int array
0.0 - for float array
\0 - for character array
Eg) int a[2]={1};
1 0 a
char b[5]={‘A’.’r’,’r’};
scanf("%d",&choice);
switch(choice)
{
case 1: mean=mean_function(array,n);
printf("\n\tMean = %f\n",mean);
break;
case 2: median=median_function(array,n);
printf("\n\tMedian = %f\n",median);
break;
case 3: mode=mode_function(array,n);
printf("\n\tMode = %f\n",mode);
break;
case 4: break;
default:
printf("Wrong Option");
break;
}
}while(choice!=4);
}
float mean_function(float array[],int n)
{
int i;
float sum=0;
for(i=0;i<n;i++)
{sum=sum+array[i];
return (sum/n);
}}
float median_function(float a[],int n)
{
float temp;int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++){
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}}
if(n%2==0)
return (a[n/2]+a[n/2-1])/2;
else
return a[n/2];
}
float mode_function(float a[],int n)
{
return (3*median_function(a,n)-2*mean_function(a,n));
}
Output
Enter Elements2
3
4
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
1
Mean = 3.000000
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
2
Median = 3.000000
Enter Choice 1.Mean
2.Median
3.Mode
4.Exit
3
Mode = 3.000000
Enter Choice
1.Mean
2.Median
3.Mode 4.Exit
4
A 2D array is an array of 1-D arrays and can be visualized as a plane that hasrows and
columns.
The elements can be accessed by using two subscripts, row subscript (rowno), column
subscript(column no).
It is also known as matrix.E.g,
1 2 3 6 7
a[3][5]
9 10 5 0 4
Declaration 3 1 2 1 6
Initialization
1. By using an initialization list, 2D array can be initialized.e.g. int
a[2][3] = {1,4,6,2}
1 4 6
2 0 0 a
// main function
int main()
{
// matrix
int a[][3] = { {5,6,7}, {8,9,10}, {3,1,2} };
int b[][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
int c[3][3];
// menu-driven
do
{
// menu to choose the operation
printf("\nChoose the matrix operation,\n");
printf("----------------------------\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Transpose\n");
printf("5. Exit\n");
printf("----------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add(a, b, c);
printf("Sum of matrix: \n");
display(c);
break;
case 2:
subtract(a, b, c);
printf("Subtraction of matrix: \n");
display(c);
break;
case 3:
multiply(a, b, c);
printf("Multiplication of matrix: \n");
display(c);
break;
case 4:
printf("Transpose of the first matrix: \n");
transpose(a, c);
display(c);
printf("Transpose of the second matrix: \n");
transpose(b, c);
display(c);
break;
case 5:
printf("Thank You.\n");
exit(0);
default:
printf("Invalid input.\n");
printf("Please enter the correct input.\n");
}
}while(1);
return 0;
}
Output:-
First Matrix:
567
8 9 10
312
Second Matrix:
123
456
789
char stringname[size];
temp_variable = strlen(string_name);
E.g.
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.
2. strcpy() function
It copies the source string to the destination stringSyntax
strcpy(destination,source);
E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome.
3. strcat() function
It concatenates a second string to the end of the first string.Syntax
strcat(firststring, secondstring);
E.g.
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is hai welcome.
E.g. Program:
#include <stdio.h>
#include <string.h>
void main ()
{
char str1[20] = "Hello";
char str3[20];
int len ;
strcpy(str3, str1);
printf("Copied String= %s\n", str3 );
strcat( str1, str2);
printf("Concatenated String is= %s\n", str1 );
len = strlen(str1);
printf("Length of string str1 is= %d\n", len );
return 0;
}
Output:
Copied String=Hello
Concatenated String is=HelloWorld
Length of string str1is
4. strcmp() function
It is used to compare 2 strings.
Syntax
temp_varaible=strcmp(string1,string2)
If the first string is greater than the second string a positive number isreturned.
If the first string is less than the second string a negative number isreturned.
If the first and the second string are equal 0 is returned.
5. strlwr() function
It converts all the uppercase characters in that string to lowercase characters.Syntax
strlwr(string_name);
E.g.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output: hello
6. strupr() function
strupr(string_name);
E.g.
str[10]= “HEllo”;
strupr(str); puts(str);
Output: HELLO
7. strrev() function
It is used to reverse the string.
strrev(string_name);
Syntax
E.g.
str[10]= “HELLO”;
strrev(str);
puts(str);
Output: OLLEH
String functions
Functions Descriptions
int val;
printf(“Enter String 1\n”);
gets(s1);
printf(“Enter String 2\n”);
gets (s2);
val=strcmp(s1,s2);
if (val==0)
printf(“Two Strings are equal”);
else
printf(“Two Strings are not equal”);
getch();
}
Output:
Enter String 1
Computer Enter
String 2
Programming
Two Strings are not equal
String Arrays
They are used to store multiple strings. 2-D char array is used for stringarrays.
Declaration
char arrayname[rowsize][colsize];
E.g.
char s[2][30];
Here, s can store 2 strings of maximum 30 characters each.
Initialization
2 ways
1. Using string constants
char s[2][20]={“Ram”, “Sam”};
2. Using initialization list. char
s[2][20]={ {‘R’, ‘a’, ‘m’, ‘\0’},
{‘S’, ‘a’, ‘m’, ‘\0’}};
E.g. Program
#include<stdio.h>
void main()
{
int i;
char s[3][20];
printf(“Enter Names\n”);
for(i=0;i<3;i++)
scanf(“%s”, s[i]);
printf(“Student Names\n”);
for(i=0;i<3;i++)
printf(“%s”, s[i]);
}
Sorting
Sorting is the process of arranging elements either in ascending or in descendingorder.
Sorting Methods
1. Selection Sort
2. Bubble Sort
3. Merge sort
4. Quick sort
1.Selection sort
In selection sort, the smallest value among the unsorted elements of the array is selected in
every pass and inserted to its appropriate position into the array. It is also the simplest algorithm. It
is an in-place comparison sorting algorithm. In this algorithm, the array is divided into two parts,
first is sorted part, and another one is the unsorted part. Initially, the sorted part of the array is
empty, and unsorted part is the given array. Sorted part is placed at the left, while the unsorted part
is placed at the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the first
position. After that second smallest element is selected and placed in the second position. The
process continues until the array is entirely sorted.
E.g.
25 20 15 10 5
5 20 15 10 25
5 10 15 20 25
#include <stdio.h>
int main()
{
int n = 10;
int a[] = {3,2,6,5,4,7,8,9,5,1};
int min_index;
for(int i = 0; i < n - 1; i++) {
min_index = i;
for(int j = i + 1; j < n; j++) {
if(a[min_index] > a[j]) {
min_index = j;
}
}
if(min_index != i)
{
int temp = a[i];
a[i] = a[min_index];
a[min_index] = temp;
}
}
printf("Sorted Array: ");
for(int i = 0; i < n; i++) {
printf(" %d", a[i]);
}
return 0;
}
Output:
Sorted Array: 1 2 3 4 5 5 6 7 8 9
2. Bubble Sort
In this method, each data item is compared with its neighbour element. Ifthey are not
in order, elements are exchanged.
With each pass, the largest of the list is "bubbled" to the end of the list.E.g.
Pass 1:
25 20 15 10 5
20 25 15 10 5
20 15 25 10 5
20 15 10 25 5
20 15 10 5 25
25 is the largest element
Repeat same steps until the list is sorted
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already in place
for j in range(0, n-i-1):
# Traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if (swapped == False):
break
# Driver code to test above
if __name__ == "__main__":
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print("Sorted array:")
for i in range(len(arr)):
print("%d" % arr[i], end=" ")
Output
Sorted array:
11 12 22 25 34 64 90
3. Merge Sort:
Merge sort is based on Divide and conquer method.
It takes the list to be sorted and divide it in half to create two unsortedlists.
The two unsorted lists are then sorted and merged to get a sorted list.
#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
int main() {
int i;
sort(0, max);
Output
List before sorting
10 14 19 26 27 31 33 35 42 44 0
List after sorting
0 10 14 19 26 27 31 33 35 42 44
4. Quick Sort
Sorting is a way of arranging items in a systematic manner. Quicksort is the widely used sorting
algorithm that makes n log n comparisons in average case for sorting an array of n elements. It is a
faster and highly efficient sorting algorithm.
This algorithm follows the divide and conquer approach.
Divide and conquer is a technique of breaking down the algorithms into subproblems, then
solving the subproblems, and combining the results back together to solve the original problem.
Divide: In Divide, first pick a pivot element. After that, partition or rearrange the array into two
sub-arrays such that each element in the left sub-array is less than or equal to the pivot element and
each element in the right sub-array is larger than the pivot element.
Conquer: Recursively, sort two subarrays with Quicksort.
Combine: Combine the already sorted array.
Quicksort picks an element as pivot, and then it partitions the given array around the picked pivot
element.
In quick sort, a large array is divided into two arrays in which one holds values that are smaller
than the specified value (Pivot), and another array holds the values that are greater than the pivot.
After that, left and right sub-arrays are also partitioned using the same approach. It will continue
until the single element remains in the sub-array.
In the given array, we consider the leftmost element as pivot. So, in this case, a[left] = 24, a[right] =
27 and a[pivot] = 24.
Since, pivot is at left, so algorithm starts from right and move towards left.
Now, a[pivot] < a[right], so algorithm moves forward one position towards left, i.e. -
Now, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so algorithm starts from left
and moves to right.
As a[pivot] > a[left], so algorithm moves one position to right as -
Now, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] > a[left], so algorithm moves one
position to right as -
Now, a[left] = 29, a[right] = 24, and a[pivot] = 24. As a[pivot] < a[left], so, swap a[pivot] and a[left],
now pivot is at left, i.e. -
Since, pivot is at left, so algorithm starts from right, and move to left. Now, a[left] = 24, a[right] = 29,
and a[pivot] = 24. As a[pivot] < a[right], so algorithm moves one position to left, as -
Now, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] > a[right], so, swap a[pivot] and
a[right], now pivot is at right, i.e. -
Now, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so the algorithm starts from left
and move to right.
Now, a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right are pointing the same
element. It represents the termination of procedure.
Element 24, which is the pivot element is placed at its exact position.
Elements that are right side of element 24 are greater than it, and the elements that are left side of
element 24 are smaller than it.
Now, in a similar manner, quick sort algorithm is separately applied to the left and right sub-arrays.
After sorting gets done, the array will be -
Program:
#include <stdio.h>
void main()
{
int i, j, temp, n, a[10];
for(i=n-1;i>=0;i--)
printf("%d\n",a[i]);
}
Output:
Enter the value of N4
Enter the numbers10
253
The numbers arranged in ascending order are given below2
3
5
10
The numbers arranged in descending order are given below10
5
3
2
Searching
Searching is an operation in which a given list is searched for a particularvalue. If the
value is found its position is returned.
Types:
1. Linear Search
2. Binary Search
1. Linear Search
Linear search is also called as sequential search algorithm. It is the simplest searching
algorithm. In Linear search, we simply traverse the list completely and match each element of
the list with the item whose location is to be found. If the match is found, then the location of
the item is returned; otherwise, the algorithm returns NULL.
It is widely used to search an element from the unordered list, i.e., the list in which
items are not sorted. The worst-case time complexity of linear search is O(n).
The steps used in the implementation of Linear Search are listed as follows -
Time Complexity
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
printf("Element is in the position %d\n",i+1);
c=1;
break;
}}
if(c==0)
printf("The number is not in the list");
getch();
}
Output:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1Enter
the number to be search: 5 Element is in the
position 3
2. Binary Search
Binary search is a fast search algorithm. This search works on the principle of divide
and conquer algorithm. The data collection should be in sorted form. The binary search looks
for a particular item by comparing middle item of the data collection. If a match occurs, then the
index of the item is returned. If the middle item is greater than the item, then the item is
searched in the sub-array to the left of the middle. Otherwise, the item is searched for in the
sub-array to the right of the middle item. This process continues on sub-array until the size of
the sub-array reduces to zero.
Example:
Consider the following sorted array and assume to search the location of value 31.
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
In this array, start is 0 and end is 9. Calculate mid of the array. Calculate mid by using formula
(start + end) / 2
mid = 0 + 9 / 2 = 9 / 2 = 4.5 ≈ 4
0 1 2 3 4 5 6 7 8 9
Compare 31 with mid element i.e. 27. Since 31 is greater than 27 perform search on right sub
array.
Now start = mid + 1 = 4 + 1 = 5 end = 9Calculate mid = (start + end) / 2
mid = (5 + 9) / 2
mid = 14 / 2 = 7
start mid end
↓ ↓ ↓
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
Compare 31 with mid element i.e. 35. Since 31 is less than 35 perform search on leftsub-array
Now end = mid - 1 = 7 - 1 = 6 start = 5Calculate mid = (start + end) / 2
mid = (5 + 6) / 2
mid = 11 / 2 = 5.5 ≈ 5
start, end
mid ↓
↓
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
Compare 31 with mid element i.e. 31. Since they are equal return the index.
Program
#include<stdio.h>
void main()
{
int a[10],i,n,m,c=0,l,u,mid;
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
}
Sample output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21Enter the
number to be search: 11
The number is found.
Example:
3 5 7 9 11
Search key=7 middle element=7
Searching element=middle element. So the element is found.Search key=11
Middle element=7 Searching
element>middle
So go to right half: 9 11. Repeat steps until 11 is found or list ends.
Time Complexity
Case Time Complexity
#include<stdio.h>
int main(){
int a[3][3], i, j;
long determinant;
printf("Enter the 9 elements of matrix: ");
for(i = 0 ;i < 3;i++)
for(j = 0;j < 3;j++)
scanf("%d", &a[i][j]);
return 0;
}
Output:
1 2 3
4 5 1
2 3 4
Determinant of 3X3 matrix: -5
Example
Input
Input elements of matrix A:
123
456
789
Input multiplier: 2
Output
2 4 6
8 10 12
14 16 18
#include <stdio.h>
#define SIZE 3 // Maximum size of the array
int main()
{
int A[SIZE][SIZE];
int num, i, j;