C program to find the smallest number in array.

Posted by Mangesh on March 16, 2018

/* Smallest number in array. */

Description :

We have a array of integers, and we need to find the smallest number in the array.

Logic :

We should store the first element in smallest variable. Then we must compare second element with smallest and store smaller element in the smallest variable, Then we must compare third element with smallest and store smaller element in the smallest variable, and so on till nth variable. At the end we with get smallest element.

Time complexity is O(n) and it requires n-1 comparisons.

Program :

#include<stdio.h>
#include<conio.h>
void main()
{
  int arr[20];
  int i,n,smallest;
  printf("Enter total number of elemnt in array : ");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
    printf("Enter %d element : ",i+1);
    scanf("%d",&arr[i]);
  }
  smallest = arr[0];
  for(i=1;i<n;i++)
  {
    if(arr[i] < smallest)
      smallest = arr[i];
  }
  printf("Smallest number is %d",smallest);
  getch();
}

Output :

C program to find smallest number.` tested in Turbo C 3.2

Skills Learned :

If-Else Statement
Loop

Written with from Mangesh.

Related Post
1 C program to reverse element in array.
2 C program to find the smallest number in array.
3 C program to find the largest number in array.
4 C program for addition of 2D matrix.
5 C program to calculate sum of all elements in array.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.