codeplayer
codeplayer

Reputation: 35

finding the largest element in an array using functions

This is the question I've tried to attempt "Given an array A[] of size n. The task is to find the largest element in it.

Input:

n = 5
A[] = {1, 8, 7, 56, 90}

Output:

90

Explanation:

The largest element of the given array is 90.
I'm unable to get the desired outcome, my output screen freezes. I think the problem is in passing by reference, please help me solve and understand my mistake

Here's my code:

#include <iostream>

using namespace std;

int largest(int* arr[], int* n) {
  int max = 0;
  for (int first = 0; first <* n; first++) {
    if (*arr[first] > max) {
      max = *arr[first];
    }

  }

  return max;
}

int main() {
  cout << "enter how many numbers you want in an array = ";
  int userinput;
  cin >> userinput;
  int* myarray=new int[userinput];
  for (int loop = 0; loop < userinput; loop++) {
    cin >> myarray[loop];
  }
  cout << "Your array = { ";
  for (int loop = 0; loop < userinput; loop++) {
    cout<< myarray[loop]<<" ";
  }
  cout << "}";
  cout << endl;
  cout<< "Largest number in the array = "<<largest(&myarray,&
                                                   userinput);
  return 0;
}

Upvotes: 0

Views: 1613

Answers (2)

Pepijn Kramer
Pepijn Kramer

Reputation: 12891

Most common problems already have a solution, in this case the standard library.

#include <algorithm>

std::array<int, 4> ar{ 1, 4, 42, 2 };
auto max_value = *std::max_element(ar.begin(), ar.end());

This will set max_value to 42. In your case you could also use a std::vector instead of an array and push_back any entries the user entered.

std::cout << "enter how many numbers you want in an array = ";
int userinput{0};
std::cin >> userinput;
std::vector<int> values;

for (int loop = 0; loop < userinput; loop++) {
    int new_value{ 0 };
    std::cin >> new_value;
    values.push_back(new_value);
}

std::cout << "Your array = { ";
for (const auto value : values)
{
    std::cout << value << " ";
}

std::cout << "}";
std::cout << std::endl;

auto max_value = *std::max_element(values.begin(), values.end());
std::cout << "Largest number in the array = " << max_value;

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

  • You should use the argument arr to read the array.
  • You should use = operator, not ==, to perform assignment.
  • You should add indentation to make your code easy to read.
  • Using fixed value for the initial value of max will make it produce wrong output when all of the elements of the array ls less than the initial value.

Fixed code:

int largest(int *arr[], int *n)
{
    if (*n <= 0) return 0;
    int max = (*arr)[0];
    for (int first = 0; first <* n; first++)
    {
        if ((*arr)[first] > max)
        {
            max = (*arr)[first];
        }

    }

    return max;
}

Upvotes: 1

Related Questions