chettinadtech.ac.inchettinadtech.ac.in/storage/14-09-12/14-09-12-14...  · web viewunit iii. 1....

40
UNIT III 1. Define arrays. Explain the array types with an example program for each type. Arrays are data structures which hold multiple variables of the same data type. Consider the case where a programmer needs to keep track of a number of people within an organization. So far, our initial attempt will be to create a specific variable for each user. This might look like, int name1 = 101; int name2 = 232; int name3 = 231; It becomes increasingly more difficult to keep track of this as the number of variables increase. Arrays offer a solution to this problem. An array is a multi-element box, a bit like a filing cabinet, and uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like other variables in C, must be declared before they can be used. The replacement of the above example using arrays looks like, int names[4]; names[0] = 101; names[1] = 232; names[2] = 231; names[3] = 0; We created an array called names, which has space for four integer variables. You may also see that we stored 0 in the last space of the array. This is a common technique used by C programmers to signify the end of an array. Arrays have the following syntax, using

Upload: vukhanh

Post on 21-Aug-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

UNIT III

1. Define arrays. Explain the array types with an example program for each type.

Arrays are data structures which hold multiple variables of the same data type. Consider the case where a programmer needs to keep track of a number of people within an organization. So far, our initial attempt will be to create a specific variable for each user.

This might look like,

int name1 = 101; int name2 = 232; int name3 = 231;

It becomes increasingly more difficult to keep track of this as the number of variables increase. Arrays offer a solution to this problem. An array is a multi-element box, a bit like a filing cabinet, and uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like other variables in C, must be declared before they can be used. The replacement of the above example using arrays looks like,

int names[4]; names[0] = 101; names[1] = 232; names[2] = 231; names[3] = 0;

We created an array called names, which has space for four integer variables. You may also see that we stored 0 in the last space of the array. This is a common technique used by C programmers to signify the end of an array. Arrays have the following syntax, using square brackets to access each indexed value (called an element).

x[i]

so that x[5] refers to the sixth element in an array called x. In C, array elements start with 0. Assigning values to array elements is done by,

x[10] = g; and assigning array elements to a variable is done by, g = x[10];

In the following example, a character based array named word is declared, and each element is assigned a character. The last element is filled with a zero value, to signify the end of the character string (in C, there is no string type, so character

based arrays are used to hold strings). A printf statement is then used to print out all elements of the array.

#include <stdio.h>

main()

{

char word[20]; word[0] = 'H'; word[1] = 'e'; word[2] = 'l'; word[3] = 'l'; word[4] = 'o'; word[5] = 0;

printf("The contents of word[] is -->%s\n", word );

}

DECLARING ARRAYS

Arrays may consist of any of the valid data types. Arrays are declared along with all other variables in the declaration section of the program.

#include <stdio.h>

main()

{

int numbers[100]; float averages[20]; numbers[2] = 10;

--numbers[2];

printf("The 3rd element of array numbers is %d\n", numbers[2]);

}

The above program declares two arrays, assigns 10 to the value of the 3rd element of array numbers, decrements this value ( --numbers[2] ), and finally prints the value. The number of elements that each array is to have is included inside the square brackets.

ASSIGNING INITIAL VALUES TO ARRAYS

The declaration is preceded by the word static. The initial values are enclosed in braces,

Example:

#include <stdio.h>

main()

{

int x;

static int values[] = { 1,2,3,4,5,6,7,8,9 };

static char word[] = { 'H','e','l','l','o' };

for( x = 0; x < 9; ++x )

printf("Values [%d] is %d\n", x, values[x]);

}

MULTI DIMENSIONED ARRAYS

Multi-dimensioned arrays have two or more index values which specify the element in the array.

multi[i][j];

In the above example, the first index value i specifies a row index, whilst j specifies a column index.

DECLARATION

int m1[10][10];

static int m2[2][2] = { {0,1}, {2,3} };

sum = m1[i][j] + m2[k][l];

NOTE the strange way that the initial values have been assigned to the two-dimensional array m2. Inside the braces are,

{ 0, 1 },

{ 2, 3 }

Remember that arrays are split up into row and columns. The first is the row, the second is the column. Looking at the initial values assigned to m2, they are,

m2[0][0] = 0 m2[0][1] = 1 m2[1][0] = 2 m2[1][1] = 3

Example:

#include <stdio.h>

main()

{

static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} };

int row, column, sum;

sum = 0;

for( row = 0; row < 4; row++ )

for( column = 0; column < 3; column++ ) sum = sum + m[row][column]; printf("The total is %d\n", sum );

}

CHARACTER ARRAYS [STRINGS]

Consider the following program,

#include <stdio.h>

main()

{

static char name1[] = {'H','e','l','l','o'}; static char name2[] = "Hello"; printf("%s\n", name1);

printf("%s\n", name2);

}

The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in name2[5], whilst name1 has not. To insert a null at the end of the name1 array, the initialization can be changed to,

static char name1[] = {'H','e','l','l','o','\0'};

Consider the following program, which initialises the contents of the character based array word during the program, using the function strcpy, which necessitates using the include file string.h

Example:

#include <stdio.h>

#include <string.h>

main()

{

char word[20];

strcpy( word, "hi there." );

printf("%s\n", word );

}

2. Write a C program to perform matrix multiplication.

PROGRAM

#include<stdio.h>main(){

      int a[25][25],b[25][25],c[25][25],i,j,k,r,s;      int m,n;      clrscr();      printf("\nEnter the Rows and Columns of A matrix...");      scanf("%d %d",&m,&n);      printf("\nEnter the Rows and Columns of B matrix...");      scanf("%d %d",&r,&s);      if(m!=r)            printf("\nThe matrix cannot multiplied");      else      {            printf("\nEnter the elements of A matrix");            for(i=0;i<m;i++)            {                  for(j=0;j<n;j++)                  scanf("\t%d",&a[i][j]);            }            printf("\nEnter the elements of B matrix");           for(i=0;i<m;i++)            {                  for(j=0;j<n;j++)                  scanf("\t%d",&b[i][j]);            }            printf("\nThe elements of A matrix");            for(i=0;i<m;i++)            {                  printf("\n");                  for(j=0;j<n;j++)                  printf("\t%d",a[i][j]);            }            printf("\n The elements of B matrix");            for(i=0;i<m;i++)            {                  printf("\n");                  for(j=0;j<n;j++)                  printf("\t%d",b[i][j]);            }            for(i=0;i<m;i++)            {                  printf("\n");

                  for(j=0;j<n;j++)                  {                        c[i][j]=0;                        for(k=0;k<m;k++)                        c[i][j]=c[i][j]+a[i][k]*b[k][j];                  }            }      }      printf("The multiplication of two matrixes");      for(i=0;i<m;i++)      {            printf("\n");            for(j=0;j<n;j++)            printf("\t%d",c[i][j]);      }      getch();} 

OUTPUT

Enter the Rows and Columns of A matrix... 3 3Enter the Rows and Columns of B matrix... 3 3Enter the elements of A matrix 1 2 3 4 5 6 7 8 9 Enter the elements of B matrix 1 2 3 4 5 6 7 8 9 The elements of A matrix      1 2 3      4 5 6      7 8 9The elements of B matrix      1 2 3      4 5 6      7 8 9The multiplication of two matrixes      30 36 42       66 81 96       102 126 150 

3. Write a C program to perform ascending and descending order of the

given numbers.

PROGRAM

#include<stdio.h>main(){      int num[100],no,i,j,a;      clrscr();      printf("Enter Upper Limit...");      scanf("%d",&no);      printf("Enter the numbers");      for(i=0;i<no;i++)            scanf("%d",&num[i]);            for(i=0;i<no-1;i++)            {                  for(j=i+1;j<no;j++)                  {                        if(num[i]<num[j])                        {                        a=num[i];                        num[i]=num[j];                        num[j]=a;                  }            }}printf("\nThe ascending order of the given numbers");for(i=0;i<no;i++)      printf("\n%d",num[i]);printf("\n The descending number of the given numbers");for(j=no-1;j>=0;j--)      printf("\n%d",num[j]);getch();}

OUTPUT

Enter the number how many number you want to sort

5Enter the numbers 10  30  50           60   20 The ascending order of the given numbers10    20  30  50  60The descending number of the given numbers60  50 30 20 10 

4. What are the string operations available in C?

strlen()

It is used to find the length of the string.

syntax:

strlen(string)

strcpy()

It is used to copy one string to another.

syntax:

strcpy(string1,string2)

strcat()

It is used to combine two strings.

syntax:

strcat(string1,string2)

strcmp()

It is used to compare two strings.

syntax:

strcmp(string1,string2)

– Returns 0 if two strings are equal.– Return value <0 if s1 is less than s2.– Return value >0 if s1 is greater than s2.

strrev()

It used to reverse a string.

syntax:

strrev(string)

strlwr()

It used to change the case of a string from upper to lower.

syntax:

strlwr(string)

strupr()

It used to change the case of a string from lower to upper.

syntax:

strupr(string)

strncpy()

It used to copy ‘n’ characters of one string to another.

strstr()

It is used to determine the first occurrence of a given string in another string.

strncat()

It Appends source string to destination string up to specified length.

strspn()

It is used t find up to what length two strings are identical.

strncmp()

It is used to compare ‘n’ character of two strings.

strcmpi()

It is used to compare two strings without regarding the case.

strnicmp()

It is used to compare first ‘n’ characters of two strings without regarding the case.

strchr()

It is used to determine the first occurrence of a given character in a string.

strrchr()

It is used to determine the last occurrence of a given character in a string.

Sample programs

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char a[]="college";

int b;

clrscr();

b=strlen(a);

printf("\nThe length of the string is %d",b);

getch();

}

Output:

The length of the string is 7

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char a[]="IT";

char b[]="Dept";

clrscr();

strcpy(a,b);

printf("\nThe string is %s",a);

getch();

}

Output:

The string is Dept

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char a[]="IT";

char b[]="Dept";

clrscr();

strcat(a,b);

printf("\nThe string is %s",a);

getch();

}

Output:

The string is ITDept

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char a[]="itdept";

char b[]="it";

int i;

clrscr();

i=strcmp(a,b);

if(i==0)

printf("\nstrings are equal:%d",i);

else if(i<0)

printf("\nstring1 is less than string2:%d",i);

else

printf("\nstring1 is greater than string2:%d",i);

getch();

}

Output:

string1 is greater than string2:100

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char a[]="itdept";

clrscr();

printf("\nThe string is :%s",a);

strupr(a);

printf("\nThe string after conversion to uppercase :%s",a);

strlwr(a);

printf("\nThe string after conversion to lowercase :%s",a);

getch();

}

The string is :itdept

The string after conversion to uppercase : ITDEPT

The string after conversion to lowercase : itdept

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char a[]="Dept";

clrscr();

printf("\nThe string is %s",strrev(a));

getch();

}

Output:

The string is tpeD

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char a[]="itdept";

char b[15];

int i=0;

clrscr();

strncpy(b,a,2);

b[2]='\0';

printf("\nThe string is :%s",b);

getch();

}

Output:

The string is : it

5. Explain what is sorting and types of sorting and explain bubble sort with example problem.

Sorting refers to the process of arranging the items in ascending or descending order according to some linear relationship among the items. It can be done on names,

numbers or records. Sorting reduces the searching time whenever we want to search any item in the given list.

There are two types of sorting techniques are there. Internal sorting External sorting Internal sorting: All the data to be sorted is stored in main memory at all times during sorting. External sorting: Data is stored outside the memory such as secondary storage devices called disk and it stores the data to a memory in small chunks. External sorting is usually applied whenever the data can't fit into memory entirely.

Bubble Sort

Bubble sort is a simple sorting algorithm that works by comparing each pair of adjacent items in the given list and swapping them if the first element is greater than the second one in each pair. This process is repeated until no swaps are needed, which indicates that the list is sorted. If we have n items to be sorted then we need n-1 passes.

ExampleLet us take the array of numbers "5 1 4 8 2", and sort the array from lowest number to greatest number using bubble sort. Totally we have 5 numbers, so we need 4 passes to complete the sorting process.First Pass:5 1 4 8 21 5 4 8 21 4 5 8 2

1 4 5 8 2 1 4 5 2 8 (Pass 1 completed)The biggest element 8 is placed in the last position of the array. It performs n-1 comparisons. Second Pass:1 4 5 2 81 4 5 2 81 4 5 2 81 4 2 5 8 (Pass 2 completed)For pass 2, we need not consider 8 for comparisons. We just consider the remaining n-1 items and perform n-2 comparisons. Now the next highest element 5 is also placed permanently.Third Pass:1 4 2 5 81 4 2 5 81 2 4 5 8 (Pass 3 Completed)During pass 3, we just make n-3 comparisons and place the next highest element 4 in the right position.Fourth Pass:1 2 4 5 81 2 4 5 8 (Bubble sort Completed)In the last pass, the remaining elements are also compared and sorted. Now we get the elements 1, 2, 4, 5 and 8 in sorted order.Algorithm

void bubble( int a[], int n ) {

int i, j; for(i=0;i<n;i++) {

for(j=1;j<(n-i);j++) {

if( a[j-1]>a[j] ) SWAP(a[j-1],a[j]);

} }

}

6. Explain insertion sorting with example. Insertion SortInsertion sort is also a simple sorting algorithm in which the elements are to be compared and swapped if necessary. Insertion sorting algorithm is similar to bubble sort but it is more efficient than bubble sort. Because the number of comparisons in insertion sort is less than the bubble sort. Insertion sort is also performs n-1 passes for n items. In each pass, we just take one item and compare with all the remaining items and place it in the right position. So, every iteration of insertion sort removes an element from the input data, since it will be placed in the correct position. This is similar to the arrangement of cards while playing.

ExampleLet us take the array of numbers "5 1 4 8 2", and sort the array from lowest number to greatest number using bubble sort. Totally we have 5 numbers, so we need 4 passes to complete the sorting process.First Pass: Take the second element and compare with the first one and place it in the right position. Here 1<5 so interchange 1 and 5 and place 1 in the first position of the array.

5 1 4 8 2 1 5 4 8 2 Second Pass:Take the third element 4 and compare with the first two items and place in the appropriate position.

1 5 4 8 2 1 4 5 8 2Third Pass:During pass 3, the 4th element 8 is compared with the first three elements and performs swapping if necessary.

1 4 5 8 2 1 4 5 8 2

Fourth Pass:Take the last element 2 compare with the first 4 elements and performs swapping then we get the elements in sorted order.

1 4 5 8 2 1 4 5 2 8

1 4 5 2 8 1 4 2 5 8

1 4 2 5 8 1 2 4 5 8

7. Explain the merge sorting concept with example. Merge Sort

The merge sort algorithm is one of the sorting techniques that are used to sort the list of elements based on the classical divide-and-conquer paradigm. Divide and Conquer method is one of the algorithm design technique that solves a problem by:1. Breaking it into sub problems that are themselves smaller instances of the same type of problem2. Recursively solving these sub problems3. Appropriately combining their answers

In merge sort, the divide and conquer that performs:DIVIDE: Divide the given array into two equal halves of n/2 elements each.CONQUER: Sort the two subsequences recursively using the merge sort.

COMBINE: Merge the two sorted subsequences of size n/2 each to produce the sorted sequence consisting of n elements.

shows the concept of merge sort. Initially we have the array of n numbers that has to be divided into two equal sub arrays. For example, if we have 8 elements, then we divide the elements into two sub arrays, each of which having 4 elements each. Again divide the sub arrays into two equal sub parts and repeat the process until the sub array has only one element. This is a dividing phase. During the conquer phase, find the solution to the sub problems, which means that arrange the elements in sub arrays in ascending order. In this phase, we just start with the sub arrays of on element that should be in sorted order. Finally in the combining phase, combine the solution of sub problems. The two sorted arrays have to be combined and arrange the list of elements in sorted order.

ExampleApply merge sort to sort the following elements 38, 27, 43, 3, 9, 82, 10. Figure 15.2 shows how the elements are to be divided and combined in the case of merge sort using divide and conquer. Initially the list consists of 7 elements. Divide the list into two equal halves, the left array contains 4 elements and right array contains 3 elements. This is a recursive process. So, the left and right array is further subdivided until the sub array contains only one element. After completing the dividing process, next we have to combining the two portions of arrays in the sorted order.

There are three pointers are used. A pointer aptr which points the first element in the left array and a pointer btr points the first element in the right array. A pointer cptr that points the first position of the element in the resultant array. During the combining phase, we just compare the elements aptr and ptr. Assign the smallest element to the cptr and increment the input array pointer (the pointer has the smallest element) and the resultant pointer. Repeat this process, until all the

elements have to be placed in the resultant array. Figure 15.3 shows the process of combining the two sorted arrays.

8. Explain the Quick sort concept with Example.

Quick Sort

Quick sort is also based on the divide and conquer algorithm that are arranging the elements in sorted order. It first divides a given array into two sub arrays that are not necessarily in equal size. The process of dividing the array which involves the

reference element called pivot. We just take one element as a pivot and compare the remaining array elements with pivot. Place the elements in the left array that are smaller than the pivot and place the elements in the right array that are greater than the pivot. It is a recursive process that divides the sub array repeatedly until the sub arrays that are having only one element. The entire process of quick sort using divide and conquer can de defines as:Divide: The array A is partitioned (rearranged) into two nonempty sub arrays

A[p . . q] and A[q+1 . . r]. The index q is a pivot element. CONQUER: The two sub arrays A[p . . q] and A[q+1 . . r] are sorted by recursive

calls to quick sort. COMBINE: Since the sub arrays are sorted in place, no work is needed to combine

them: the entire array A is now sorted.

Figure 15.4 – Quick sort using Divide and ConquerThe steps are:

1. Pick an element, called a pivot, from the list.2. Reorder the list so that all elements with values less than the pivot come

before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.

The base case of the recursion are lists of size zero or one, which never need to be sorted. The time complexity of quick sort depends upon the how to choose the pivot element. There are three ways to select to a pivot. Either we have to take the first element as a pivot, or the last element as a pivot or a middle element as a

pivot. The number of interchanges that may be varied because of pivot element. In our example, we have to choose the last array element as a pivot.

Consider the following elements 1, 12, 5, 28, 7, 14, 3, 8 and 11. Sort these elements using quick sort. In this example, we just take the last array element as a pivot.

Steps1. Take the last element as a pivot element.2. Set pointer i to a[i] and j to a[n-1].3. Compare pivot with a[i].4. If a[i] is smaller than pivot then increment i by 1.5. Otherwise, compare a[j] with pivot.6. If a[j] is greater than pivot, then decrement j by 1.7. Otherwise, compare i and j.8. If I is smaller than j, repeat steps from 3 to 7.9. Otherwise, swap a[i] with pivot.

10.Now the array is divided into two sub arrays. Repeat the entire steps for left array an then right array.

void q_sort( input_type a[], int left, int right ){

int i, j;input_type pivot;

while( a[++i] < pivot ); while( a[--j] > pivot ); if( i < j )

swap( &a[i], &a[j] );else

break;

}swap( &a[i], &a[right-1] ); /*restore pivot*/q_sort( a, left, i-1 );q_sort( a, i+1, right );

9. Explain the types of searching available?

SearchingSearching is a method of finding the element or items is present in the given set or list. If the element is found then we return the corresponding position. Otherwise return an error message. It can be applied in many real life situations such as search a word in the dictionary, search a phone number in the telephone directory, search the address in the street and so on. But in this searching method, the time complexity is very much important because the searching method is definitely find the accurate solutions but the fact is about how much time.Searching can be classified into:

Linear search Binary search

Linear search is also called as sequential search. As the name implies, the searching process is done in linear or sequential manner in linear search. It starts searching with the first item, If the item is not matched with the search item, then we go for the second item, third item and so on. If any item is matched with the search item, then we stop the execution of searching process and return the corresponding position.The searching process starts with the middle item. If the search item is less than the middle item, then we repeat the process in left side of the array. Otherwise, we go for the right side of the array. Binary search is better than the linear search, since it takes vey less number of comparisons while we searching. But it takes some time for sorting the items.

Linear Search One of the most straightforward and a simple search method is the sequential search, also known as a linear search. Linear search or sequential search is a

method for finding whether an item is available in the given list or not. In linear search, we just start the searching process with the first element. If the search element is matched with the first element of the list, then we return the corresponding position. Otherwise, compare the next element of the list. This process is continues until we found an item or we reach the end of an array.

StepsStep 1: Get the search item X and the input array A with size n.Step 2: Compare the search item X with the first item i.e., a[0]. Step 3: If it is matched, then return the corresponding position of the array element and exit from the program.Step 3: Otherwise, increment the array index by 1 and compare the array element with X.Step 4: Repeat the process, until we find the solution or we reach the end of an array. Step 5: If the element is not found in the given array, and we reach the end of an array, then display the error as “Element is not found”

Algorithm

ExampleConsider an array that consists of the elements “11, 3, 5, 27, 18 and 51”. Search the item X=18 in the array using linear search.

Linear_Search (A, X)For i0 to n-1 do

If a[i] = X thenPrint “Element is Found in location i”

If ( i > n)Print “Element is not available”

Binary Search

A binary search algorithm search an item in the given list. If the item is found then it returns the position of the array, Otherwise it returns the error message. In this type of binary search, the elements in the array are already sorted. It starts searching by comparing the element at the middle position. All the elements which are smaller than middle element are placed in the left of the middle one and all the elements which are greater than the middle one are placed in eth right position of the middle element. In each step, the algorithm compares the input key value with the middle element of the array. If the search key matches with the middle element, then an index, or position, is returned. Otherwise, compare the search item with the middle one. If the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned.

AlgorithmAlgorithm is quite simple. It can be done either recursively or iteratively:1. Get the middle element;2. If the middle element equals to the searched value, the algorithm stops;3. Otherwise, two cases are possible:

o Searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element.

o Searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element.

Procedure

Figure 13.12 – Binary Search Example

Example

Linear Search Binary SearchA linear search works by looking at A binary search comes with the prerequisite

int binarySearch(int arr[], int value, int left, int right)while (left <= right) do

int middle = (left + right) / 2;if (arr[middle] == value)

return middle;else if (arr[middle] > value)

right = middle - 1;else

left = middle + 1;return -1;

each element in a list of data until it either finds the target or reaches the end.

that the data must be sorted.

A linear search starts at the beginning of a list of values, and checks 1 by 1 in order for the result you are looking for.

A binary search starts in the middle of a sorted array, and determines which side (if any) the value you are looking for is on. That "half" of the array is then searched again in the same fashion, dividing the results in half by two each time.

Linear search doesn't requires the input data to be sorted

Binary search requires the input data to be sorted

Linear search only requires equality comparisons

Binary search requires an ordering comparison

Linear search has complexity O(n) as discussed earlier

Binary search has complexity O(log n)

Linear search only requires sequential access (this can be very important - it means a linear search can stream data of arbitrary size)

Binary search requires random access to the data