0
How would I do this C++ Beginners. And break it down for me Thanks.
I'm doing some homework problems and I come across to the following An array of integers which returns the smallest element getsmallest [{1,5,-3,9},4] ---> -3 getsmallest [{2,5,9,5},4] ---> 2 getsmallest [{7,7,7},3] ---> 7 So in the code int getsmallest (int a[ ], int x) { //code here }
3 ответов
+ 4
The procedure is simple, all you need is a variable to keep track of the smallest value and a loop. First, initialize the value of your variable to the first element of the array. Then you iterate over the remaining elements, e.g. with a for loop, and inside the loop, you check whether the current element is smaller than your variable with an if-statement. If the current element is indeed smaller, you update the value of your variable with the current element, otherwise nothing needs to happen. Once the loop ends, you can simply return the variable, which will then hold the value of the smallest element.
+ 2
You can also use the min_element function which belongs to the ALGORITHM library (It will return a pointer to the smallest element).
#include <algorithm>
int arr[4] = {1, 2, 5, 3};
cout << *min_element(arr, arr + 4); // it will be 1
0
Thanks Shadow I figured it out sorry for the late response