Find Smallest element and it’s position of an Array

Description

To find the smallest element of an array, Assume any element of array as smallest.
Here assuming first element as smallest. Now compare every elements of array to
first element. If array element is less than element which assumed as smallest, 
update the smallest element to that element.

C/C++

/*C program to print smallest element of the array*/
//Save it as PositionOfSmallestNumber.c

#include<stdio.h>
int main(){

    int i,n;

    printf("Enter the size of array : ");
    scanf("%d",&n);

    int arr[n];

    printf("Enter the elements of the array : ");
    for(i=0;i<n;i++) {
        scanf("%d",&arr[i]);
    }

    
    /*Assuming first element is smallest*/
    
    int min = arr[0];
    int pos = -1;

    for(i=0;i<n;i++) {
        if(arr[i] < min) {
            min = arr[i];
            pos = i;
        }
    }

    printf("The smallest elements is : %d\n", min);
    printf("Position of smallest element is : %d", (pos+1));
}
Input:
Enter the size of array :
5
Enter the elements of the array :
6
1
2
8
3
Output:
The smallest elements is : 1
Position of smallest element is : 2

Java

/*Java program to print smallest element of the array*/
//Save it as PositionOfSmallestNumber.java

import java.io.*;
import java.util.Scanner;

public class PositionOfSmallestNumber {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the size of array : ");
        int n = scanner.nextInt();
        
        int arr[] = new int[n];
        
        System.out.println("Enter the elements of the array : ");
        for(int i=0;i<n;i++) {
            arr[i] = scanner.nextInt();
        }
        
        /*Assuming first element is smallest*/
        
        int min = arr[0];
        int pos = -1;
        
        for(int i=0;i<n;i++) {
            if(arr[i] < min) {
                min = arr[i];
                pos = i;
            }
        }
        
        System.out.println("The smallest elements is : " + min);
        //Since index starts from 0, print position as pos+1
        System.out.println("Position of smallest element is : " + (pos+1));
    }
}
Input:
Enter the size of array :
5
Enter the elements of the array :
6
1
2
8
3
Output:
The smallest elements is : 1
Position of smallest element is : 2

Related Programs

1) Program for finding Second Largest Element Of Array
2) Program to swap maximum and minimum element of Array
3) Program to Find the smallest missing number
4) Program to Find K largest elements from array
5) Program to find maximum and second maximum if elements of array is space separated input
6) Program to make pair of elements alternatively
7) Remove Duplicate Elements From Array
8) Program to Read and Display entered numbers using an Array
9) Program to merge two sorted arrays
10) Program to read and display 2D array
Share Me

Leave a Reply