codescracker
c

C Program to Find Smallest Number in an Array



« Previous Program Next Program »

In this tutorial, you will learn and get code about finding the smallest number in an array with and without using user-defined function.

To find the smallest element from given array in C programming, you have to ask from user to enter all the elements for an array. Then find smalls from all as shown in the program given below:

#include<stdio.h>
#include<conio.h>
int main()
{
    int arr[10], small, i;
    printf("Enter 10 Array Elements: ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    i=0;
    small=arr[i];
    while(i<10)
    {
        if(small>arr[i])
            small = arr[i];
        i++;
    }
    printf("\nSmallest Number = %d", small);
    getch();
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample run:

c program find smallest element in array

Now supply any 10 numbers as array elements say 10, 8, 9, 3, 7, 1, 2, 4, 6, 5 and ENTER key to see the following output:

c smallest number in array

After receiving the input, that is 10 numbers from user, as array elements. Value at index no.0 (first number) gets initialized to small variable (assuming that the first number is the smallest one). Then compares it with rest of 9 numbers one by one using while loop and checks whether it is greater or not. If it is, then simply initialize that value to small and continue to check for value at next index, until compared with all the 10 numbers. Finally print the value of small as output.

Using User-defined Function

Let's create another program that does the same job with an extra feature added to it. The extra feature is, this program allows user to define the size for array, then enter elements of given size. This program finds smallest using a user-defined function findSmallest().

#include<stdio.h>
#include<conio.h>
int findSmallest(int [], int);
int main()
{
    int arr[50], small, i, size;
    printf("Enter Array Size: ");
    scanf("%d", &size);
    printf("Enter %d Array Elements: ", size);
    for(i=0; i<size; i++)
        scanf("%d", &arr[i]);
    small=findSmallest(arr, size);
    printf("\nSmallest Number = %d", small);
    getch();
    return 0;
}
int findSmallest(int arr[], int n)
{
    int i=0, small;
    small=arr[i];
    while(i<n)
    {
        if(small>arr[i])
            small = arr[i];
        i++;
    }
    return small;
}

Here is its sample run:

find smallest number in array c

Same Program in Other Languages

C Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker