Problem
: Given an array of integers ,find the smallest element in it.
Examples:
Input :
array[]={12,34,65,98,15,34}
Output :
12
Input :
array[]={22,30,95,90,15,54}
Output :
15
Solution:
- We assume that first element of the array is the smallest one.
- Then iterate the array and compare each element with the assumed smallest element.
- If current element is smaller than assumed smallest element, we update the assumed smallest element to current element. This process continues till all elements are checked.
//
C program to find the smallest element in an array
#include<stdio.h>
int
main(){
int array[]={76,90,87,98,56,77,91};
int min,arraySize=0;
//function declaration
int minElement(int array[],int n);
//finding the size(no of elements) of array
arraySize = sizeof(array)/ sizeof(int);
//function calling
min = minElement (array,arraySize);
printf("Smallest Element is %d.\n",
min);
return 0;
}
//function
definition
int minElement(int array[],int n){
int min,i;
min =array[0]; //assume that first element is the smallest
one
for (i = 1; i < n; i++){
if (array[i]< min){
min=array[i];
}
}
return min;
}
Output:
.
Please comment if you find anything incorrect, or you want to improve the topic discussed above.
No comments:
Post a Comment