Get minimum value in the array

Contents

Output

1

Code examples


C

#include <stdio.h>

static int minValue(const int* array, int size) {
    size_t i;
    int min;
    min = array[0];
    for (i = 1; i < size/sizeof(array[0]); ++i) {
        if (min > array[i]) {
            min = array[i];
        }
    }
    return min;
}

int main(void) {
    const int array[] = {3, 1, 2};
    printf("%i\n", minValue(array, sizeof(array)) );
}

C++

#include <iostream>
using namespace std;

int main() {
    int array []= {3, 1, 2};
    int smallest = array[0] ;
    for ( int i=1;  i < sizeof(array)/sizeof(array[0]);  ++i ) {
        if ( array[i] < smallest ) {
             smallest = array[i] ;
        }
    }
    cout << smallest << '\n' ;
    return 0;
}

Java

Min.java

public class Min {
    public static void main(String[] args) {
        int[] myList = {3, 1, 2};
        int min = getMin(myList);
        System.out.println(min);
    }
    
    public static int getMin(int[] inputArray){ 
        int minValue = inputArray[0]; 
        for(int i=1;i<inputArray.length;i++){ 
            if(inputArray[i] < minValue){ 
                minValue = inputArray[i]; 
            } 
        } 
        return minValue; 
    }
}

JavaScript

let array = [3, 1, 2]
console.log(Math.min(...array))

Perl

use List::Util 'min';
my @array = (3, 1, 2);
print min(@array)."\n";

PHP

<?php
$array = [3, 1, 2];
print(min($array)."\n");

Python

array = [3, 1, 2]
print(min(array))

Ruby

array = [3, 1, 2]
print(array.min + "\n")

Shell

#!/bin/sh
array=(3 1 2)
min=${array[0]}
for i in ${array[@]}
do
    if [ ${i} -lt $min ]; then
        min=${i}
    fi
done
echo $min;