C Program To Find Smallest Number In An Array So Easy

C program to find smallest number in an array with easy logic and simple example and test case.

Example:
Input Array: 2 6 4 8 9
Output: 2

LOGIC:

  • Create an integer variable and store first element of the array into it, assuming this is smallest value.
  • Traverse the array using for a loop from location 1 to array length -1. 0th location we have already stored in smallest variable.
  • Check if current element is smaller than value stored in smallest variable. If it is smaller, then assign the smallest variable with current array location value.
  • Once loop is over, smallest variable contains smallest value.

C Program To Find Smallest Number In An Array

/* --------------------------------------------------
* C Program to find smallest number in Array
*/
#include<stdio.h>
 

/* --------------------------------------------------
* C function to find smallest number / element
* in an integer array
*
* @ parameters:
* int*arr : It accept base address of int array
* int len : length of the array
*
*
* @ return : It returns the smallest / minimum
* value from array
*/

int findSmallest( int *arr, int len){
 
int smallest, i;
 
smallest = arr[0];//assume first element as smallest
//Start loop from 1st location as smallest hold the
//0th location value.

for(i=1; i<len; i++)
{

/* If current element is smaller than min */
 if(arr[i] < smallest)
 {
   smallest = arr[i];
 }
}
 
 return smallest;
}



/* --------------------------------------------------
*     C TEST PROGRAM
*/
int main()
{
int smallestNumber;
int arr[30];//you can change the capacity
int index,size;

 
/* Enter size of the int array */
printf("Enter The Size of array: ");
scanf("%d", &size);

/* Input array elements */
printf("Enter elements: ");

for(index=0; index<size; ++index)
{
 scanf("%d", &arr[index]);
}

//Call function to get smallest number

 smallestNumber = findSmallest(arr, size);
 printf("Smallest Element = %d", smallestNumber);
 
return 0;
}

Output:


Test Case-1:
Enter The Size of array: 5
Enter elements: 2 6 4 8 9
Smallest Element = 2

Test Case-2 – Check with duplicates
Enter The Size of array: 5
Enter elements: 6 6 2 5 9
Smallest Element = 2Press any key to continue . . .

Test Case-3 – Includes negative elements
Enter The Size of array: 5
Enter elements: 3 2 -10 7 9
Smallest Element = -10

Related Posts