0% found this document useful (0 votes)
15 views37 pages

New UNIT-III

C programming unit III study material

Uploaded by

123niggo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views37 pages

New UNIT-III

C programming unit III study material

Uploaded by

123niggo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT-III ARRAYS AND STRINGS

Introduction to Arrays: Declaration, Initialization – One dimensional array – Two


dimensional arrays - String operations: length, compare, concatenate, copy – Selection
sort, linear and binary search.
Introduction to Arrays

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)

1.2 3.5 5.4 2.1


b(float array )

[0] [1] [2] [3]

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.

iii) The array index in c starts with 0.

In general arrays are classified as:

1. Single dimensional array

2. Multi-dimensional array
Declarations of Arrays

Array has to be declared before using it in C Program. Declaring Array means specifying three
things.

Data_type Data Type of Each Element of the array

Array_name Valid variable name

Size Dimensions of the Array Arrays

are declared using the following syntax:

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.

ex: int marks[10]


Initialization of arrays

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,

type array_name[size] = { list of values};

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.

ex: int marks[5] = {90, 92, 78, 82, 58};

One dimensional Array

 It is also known as one-dimensional arrays or linear array or vectors


 It consists of fixed number of elements of same type
 Elements can be accessed by using a single subscript. eg) a[2]=9;
Eg)

1 3 5 2

a
[0] [1] [2] [3] subscripts or indices

Declaration of Single Dimensional Array


Syntax:
datatype arrayname [array size];

E.g. int a[4]; // a is an array of 4 integers char


b[6]; //b is an array of 6 characters

Initialization of single dimensional array


Elements of an array can also be initialized.
Rules
a) Elements of an array can be initialized by using an initialization list. An initialization list
is a comma separated list of initializers enclosed within braces.
Eg) int a[3]={1,3,4};

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’};

b ‘A’ ‘r’ ‘r’ ‘\0’ ‘\0’


Usage of single dimensional array
The elements of single dimensional array can be accessed by using asubscript
operator([]) and a subscript.
Reading storing and accessing elements:
An iteration statement (i.e loop) is used for storing and reading elements.
Ex:1 Program to calculate the average marks of the class
#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float avg;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
avg=(float)sum/n;
printf(“average=%f”,avg);
}
Output:
Enter number of students5
Enter marks of students55
60
78
85
90
Average=73.6
Example Programs
C Program to Find Mean, Median, and Mode of Given Numbers.
#define SIZE 100
#include"stdio.h"
float mean_function(float[],int);
float median_function(float[],int);
float mode_function(float[],int);
int main()
{
int i,n,choice;
float array[SIZE],mean,median,mode;
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i scanf("%f",&array[i]);
do
{
printf("\n\tEnter Choice\n\t1.Mean\n\t2.Median\n\t3.Mode\n4.Exit");

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

Two dimensional Array

 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

datatype arrayname [row size][column size]

e.g) int a [2][3]; //a is an integer array of 2 rows and 3 columnsnumber


of elements=2*3=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

2. The initializers in the list can be braced row wise.e.g int


a[2][3] = {{1,4,6} , {2}};
Example Program
Progarm for addition,transpose and multiplication of array
#include<stdio.h>
#include<stdlib.h>

// function to add two 3x3 matrix


void add(int m[3][3], int n[3][3], int sum[3][3])
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
sum[i][j] = m[i][j] + n[i][j];
}

// function to subtract two 3x3 matrix


void subtract(int m[3][3], int n[3][3], int result[3][3])
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
result[i][j] = m[i][j] - n[i][j];
}

// function to multiply two 3x3 matrix


void multiply(int m[3][3], int n[3][3], int result[3][3])
{
for(int i=0; i < 3; i++)
{
for(int j=0; j < 3; j++)
{
result[i][j] = 0; // assign 0
// find product
for (int k = 0; k < 3; k++)
result[i][j] += m[i][k] * n[k][j];
}
}
}

// function to find transpose of a 3x3 matrix


void transpose(int matrix[3][3], int trans[3][3])
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
trans[i][j] = matrix[j][i];
}

// function to display 3x3 matrix


void display(int matrix[3][3])
{
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
printf("%d\t",matrix[i][j]);

printf("\n"); // new line


}
}

// 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];

// print both matrix


printf("First Matrix:\n");
display(a);
printf("Second Matrix:\n");
display(b);

// variable to take choice


int choice;

// 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

Choose the matrix operation,


----------------------
1. Addition
2. Subtraction
3. Multiplication
4. Transpose
5. Exit
----------------------
Enter your choice: 1
Sum of matrix:
6 8 10
12 14 16
10 9 11

Choose the matrix operation,


----------------------
1. Addition
2. Subtraction
3. Multiplication
4. Transpose
5. Exit
----------------------
Enter your choice: 2
Subtraction of matrix:
444
444
-4 -7 -7

Choose the matrix operation,


----------------------
1. Addition
2. Subtraction
3. Multiplication
4. Transpose
5. Exit
----------------------
Enter your choice: 3
Multiplication of matrix:
78 96 114
114 141 168
21 27 33

Choose the matrix operation,


----------------------
1. Addition
2. Subtraction
3. Multiplication
4. Transpose
5. Exit
----------------------
Enter your choice: 4
Transpose of the first matrix:
583
691
7 10 2
Transpose of the second matrix:
147
258
369

Choose the matrix operation,


----------------------
1. Addition
2. Subtraction
3. Multiplication
4. Transpose
5. Exit
----------------------
Enter your choice: 6
Invalid input.
Please enter the correct input.

Choose the matrix operation,


----------------------
1. Addition
2. Subtraction
3. Multiplication
4. Transpose
5. Exit
----------------------
Enter your choice: 5
Thank You
String Operations
Definition:
The group of characters, digits, & symbols enclosed within double quotes iscalled as
Strings. Every string is terminated with the NULL (‘\0’) character.
E.g. “INDIA” is a string. Each character of string occupies 1 byte ofmemory.
The last character is always ‘\0’.
Declaration:
String is always declared as character arrays.
Syntax

char stringname[size];

E.g. char a[20];


Initialization:
We can use 2 ways for initializing.
1. By using string constant
E.g. char str[6]= “Hello”;
2. By using initialisation list
E.g. char str[6]={‘H’, ‘e’, ‘l’, ;l’, ;o’, ‘\0’};

String Operations or String Functions


These functions are defined in string.h header file.
1. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is notcounted.
Syntax

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 str2[20] = "World";

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);

It converts all the lowercase characters in that string to uppercase characters.Syntax

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

strlen() Determines the length of a String

strcpy() Copies a String from source to destination

strcmp() Compares two strings

strlwr() Converts uppercase characters to lowercase

strupr() Converts lowercase characters to uppercase

strdup() Duplicates a String

strstr() Determines the first occurrence of a given String in another string

strcat() Appends source string to destination string

strrev() Reverses all characters of a string

Example: String Comparison


void main()
{
char s1[20],s2[20];

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];

void merging(int low, int mid, int high) {


int l1, l2, i;

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++];
}

while(l1 <= mid)


b[i++] = a[l1++];

while(l2 <= high)


b[i++] = a[l2++];

for(i = low; i <= high; i++)


a[i] = b[i];
}

void sort(int low, int high) {


int mid;

if(low < high) {


mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}

int main() {
int i;

printf("List before sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);

sort(0, max);

printf("\nList after sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);
}

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.

Choosing the pivot


Picking a good pivot is necessary for the fast implementation of quicksort. However, it is typical to
determine a good pivot. Some of the ways of choosing a pivot are as follows -
Pivot can be random, i.e. select the random pivot from the given array.
Pivot can either be the rightmost element of the leftmost element of the given array.
Select median as the pivot element.

Working of Quick Sort Algorithm


Now, let's see the working of the Quicksort Algorithm.
To understand the working of quick sort, let's take an unsorted array. It will make the concept more
clear and understandable.
Let the elements of array are -

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] = 24, a[right] = 19, and a[pivot] = 24.


Because, a[pivot] > a[right], so, algorithm will swap a[pivot] with a[right], and pivot moves to right,
as -

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];

printf("Enter the value of N \n");


scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("The numbers arranged in ascending order are given below \n");

for (i = 0; i < n; i++)


printf("%d\n", a[i]);
printf("The numbers arranged in descending order are given below \n");

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 -

o First, we have to traverse the array elements using a for loop.


o In each iteration of for loop, compare the search element with the current array element, and -
o If the element matches, then return the index of the corresponding array element.
o If the element does not match, then move to the next element.
o If there is no match or the search element is not present in the given array, return -1.

Time Complexity

o Case Time Complexity


o Best Case O(1)
o Average Case O(n)
o Worst Case O(n)

The space complexity of linear search is O(1).


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0;
clrscr();
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");

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

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. 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;

printf("Enter the size of an array: ");


scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");

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

Best Case O(1)

Average Case O(logn)

Worst Case O(logn)

The space complexity of binary search is O(1).


Write a program in C to calculate the determinant of a 3 x 3 matrix.
Pictorial Presentation:

#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]);

printf("\nThe matrix is\n");


for(i = 0;i < 3; i++){
printf("\n");
for(j = 0;j < 3; j++)
printf("%d\t", a[i][j]);
}
determinant = a[0][0] * ((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1] * (a[1][0]
* a[2][2] - a[2][0] * a[1][2]) + a[0][2] * (a[1][0] * a[2][1] - a[2][0] * a[1][1]);

printf("\nDeterminant of 3X3 matrix: %ld", determinant);

return 0;
}

Output:

Enter the 9 elements of matrix: 1 2 3 4 5 1 2 3 4


The matrix is

1 2 3
4 5 1
2 3 4
Determinant of 3X3 matrix: -5

C program to perform Scalar matrix multiplication

Example
Input
Input elements of matrix A:
123
456
789
Input multiplier: 2
Output
2 4 6
8 10 12
14 16 18

Scalar multiplication of matrix


Scalar multiplication of matrix is the simplest and easiest way to multiply matrix. Scalar
multiplication of matrix is defined by –
(cA)ij = c . Aij (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n)

Program to perform scalar matrix multiplication

#include <stdio.h>
#define SIZE 3 // Maximum size of the array
int main()
{
int A[SIZE][SIZE];
int num, i, j;

/* Input elements in matrix from user */


printf("Enter elements in matrix of size %dx%d: \n", SIZE, SIZE);
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
scanf("%d", &A[i][j]);
}
}

/* Input multiplier from user */


printf("Enter any number to multiply with matrix A: ");
scanf("%d", &num);

/* Perform scalar multiplication of matrix */


for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
A[i][j] = num * A[i][j];
}
}

/* Print result of scalar multiplication of matrix */

printf("\nResultant matrix = \n");


for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
printf("%d ", A[i][j]);
}
printf("\n");
}
return 0;
}

You might also like