mardi 25 février 2020

Finding smallest value in an array with C++ [duplicate]

I am a C++ beginner and would like to find the smallest value in an array.

In JAVA, no problem at all.

JAVA

public class Algorithm {
    public int smallest(int[] a) {
        int smallest = a[0];
        for (int i = 1; i < a.length; i++) {
            if (smallest > a[i]) {
                smallest = a[i];
            }
        }
        return smallest;
    }
    public static void main(String[] args) {
        int[] numbers = { 3, 5, 6, -12, -36, 5, 6, 7, -37 };
        Algorithm al = new Algorithm();
        System.out.print(al.smallest(numbers));
    }
}

But in C++ - I cannot find a solution to loop thru an array.

C++

#include <iostream>

int smallest(int a[]) {
    int smallest = a[0];
    for(int i = 1; i < a."whatComeHere??"; i++){
        if(smallest > a[i]) {
            smallest = a[i];
        }
    }
    return smallest;
}
int main() {
    int numbers[] = { -5, 2, 4, -6, 5, 6, 7, 8, -3, -56 };
    std::cout << smallest(numbers) << std::endl;
    return 0;
}

Thanks for any help. I appreciate that.

Aucun commentaire:

Enregistrer un commentaire