Trouble Finding lowest value in array in C++ -
help me find out minimum value array in function4. getting 0 every time. value present @ first index of array minimum value. kindly review code , me solve problem.
#include <iostream> using namespace std; int count=0; void function1(int a[]) { (count=0;count<100;count++) { cin >> a[count]; if (a[count]==0) break; } } int function2 (int a[]) { int sum=0,avg=0; (int n=0;n<count;n++) { sum=sum+a[n]; } avg=sum/count; return avg; } //maximum value int function3 (int a[]) { int max1=a[0]; (int count=0;count<100;count++) { if (a[count]>max1) max1=a[count]; } return max1; } //minimum value int function4 (int a[]) { int min1=a[0]; (int count=0;count<100;count++) { if (a[count]<min1){ min1=a[count];} } return min1; } int main () { int a[100]={0}; function1(a); cout <<"average : "<<function2(a)<<'\n'; cout <<"maximum value : "<<function3(a) <<'\n'; cout <<"minimum value : "<<function4(a) << '\n'; }
it looks trying learn programming itself, , not c++. if how c++ gets smaller element in container, i'd advise stl documentation std::min_element()
. has been asked here before: how find minimum value vector?
but surely still need few hints before:
- name functions intuitively.
function4
terrible name function meaning find lowest/smallest/minimum value in container. how callingminimum
? - allways search before posting. stackoverflow smart enough search while type.
- the way pass array functions problem. have function makes assumptions on array size no guaranties. if change declaration
a[100]
a[10]
program accessing data outside array bounds.there many solutions it. include parameter telling array size or usestd::vector
, example. 1.please study how parameters (specially arrays) can passed in c++. take @ passing arrays , functions safely , securely begin. - important: data being populated
function1()
through console input. ** are sure filling in 100 values in array , none zero? ** if have0
in array , no negative inputs,minimum
value0
!
Comments
Post a Comment