Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Exercise 5 a) Write a C program to interchange the largest and smallest numbers in the array.

b) Write a C program to implement a liner search. c) Write a C program to implement binary search

1. Write a C program to interchange the largest and smallest numbers in the array.
#include<stdio.h> main( ) { float value[4] = {2.5,-4.75,1.2,3.67}; clrscr(); largest(value,4); smallest(value,4); getch(); } largest(float a[], int n) { int i; float max; max = a[0]; for(i = 1; i < n; i++) if(max < a[i]) max = a[i]; printf("\n Maximum number is:%f",max); } smallest(float a[], int n) { int i; float min; min = a[0]; for(i = 1; i < n; i++) if(min > a[i]) min = a[i]; printf("\n Least number is:%f",min); } Input/ Output: Maximum Number is: 3.670000 Minimum Number is: -4.750000

2. Write a C program to implement a liner search


#include <stdio.h> int main() { int array[100], search, c, number; printf("Enter the number of elements in array\n"); scanf("%d",&number); printf("Enter %d numbers\n", number); for ( c = 0 ; c < number ; c++ ) scanf("%d",&array[c]); printf("Enter the number to search\n"); scanf("%d",&search); for (c =0;c<number;c++ ) { if(array[c]== search )/* if required element found */ { printf("%d is present at location %d.\n", search, c+1); break; } } if ( c == number ) printf("%d is not present in array.\n", search); return 0; } Input/ Output: Enter the number of elements in array 4 Enter 4 numbers 22 33 44 55 Enter the number to search 44 44 is present at location 3.

3. Write a C program to implement binary search


#include <stdio.h> int main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\n"); scanf("%d",&n); printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); printf("Enter value to find\n"); scanf("%d",&search); first = 0; last = n - 1; while( first <= last ) { middle = (first+last)/2; if ( array[middle] < search ) first = middle + 1; else if ( array[middle] == search ) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; } if ( first > last ) printf("Not found! %d is not present in the list.\n", search); return 0; } Input/ Output

SAME AS THE ABOVE PROGRAM

You might also like