Reputation: 29
Here's my code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void buildArray(int arr[], int size) {
srand(time(NULL));
for (int i = 0; i < size; ++i) {
arr[i] = rand() % 100 + 1;
}
}
void showArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << i << arr[i] << " ";
}
}
void curveArray(int arr[], int size, int curve) {
for (int i = 0; i < size; ++i) {
arr[i] += curve;
}
}
int maxNum(int arr[], int size) {
int maxnum = arr[0];
int position = 0;
for (int i =1; i < size; ++i) {
if (arr[i] > maxnum ) {
maxnum = arr[i];
position = i;
}
}
return position;
}
int minNum(int arr[], int size) {
int minnum = arr[0];
int position = 0;
for (int i =1; i < size; ++i) {
if (arr[i] < minnum) {
minnum = arr[i];
position = i;
}
}
return position;
}
int main()
{
const int size = 10;
int arrayx[size];
buildArray(arrayx, size);
showArray(arrayx, size);
//curveArray(arrayx, size, 5);
//showArray(arrayx, size);
int maxVal = maxNum(arrayx, size);
cout << endl << endl << maxVal;
int minVal = minNum(arrayx, size);
cout << endl << endl << minVal;
return 0;
}
Whenever I try to run this code it generates a random array (as it's supposed exactly) but then when I use the functions to get the Max and Min Values it generates random number so here's the output when I run it
http://imageshack.com/a/img27/725/4jv9.png
This is from a C++ practice video but It works with the tutor but not with me and it's almost the same code!!
Upvotes: 1
Views: 775
Reputation: 17053
Your code returns positions of min and max values. To take values use
int maxVal = arrayx[maxNum(arrayx, size)];
cout << endl << endl << maxVal;
int minVal = arrayx[minNum(arrayx, size)];
cout << endl << endl << minVal;
also your showArray
is incorrect. Change it to
void showArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
}
Upvotes: 1
Reputation: 5297
You are returning position of Max
and Min
value from the function, not the actual max
and min
values. It should be
return arr[position];
instead of
return position;
Upvotes: 1