Click here to Skip to main content
14,984,270 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Given an array A[] of size n. The task is to find the largest element in it.


Example 1:

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

Output: 90
Explanation:
The largest element of given array is 90.

What I have tried:

i don't know how to use the return statement here
Posted
Updated 21-Mar-21 21:32pm
v2
Comments
Patrice T 22-Mar-21 3:19am
   
'i don't know how to use the return statement here '
And you can't read the documentation ?
Richard Deeming 22-Mar-21 4:49am
   
REPOST
You have already posted this homework assignment in the Java forum:
how to do it - Java Discussion Boards[^]

   
Comments
CPallini 22-Mar-21 3:25am
   
5.
Maciej Los 22-Mar-21 3:27am
   
Thank you, Carlo.
When you write a Java method[^] you can specify a return type - a type of value that the method passes back to the caller when it is finished. The return type can be anything: integer, double, boolean, a class you wrote: any single type name that you can put in front of a variable name when you declare it.

And the system then knows that you will provide a value when the method is called. To provide that value, you use the return statement supplying the value to return.
For example, a JAva method to add two numbers could be:
Java
static int Add(int x, int y){
   int result = x + y;
   return result;
}
This takes two parameters called x and y both of which are integers, adds them together, and returns the resulting value.

Your need for a return in your code means you probably need a method which accepts an array of integers, and returns an integer:
Java
static int GetBiggest(int[] arr){
   int biggest;
   ...
   return biggest;
}
All you need to do is fill in the code in the middle.
   
Comments
Maciej Los 22-Mar-21 4:16am
   
5ed!
Try
Java
public class Max
{ 
  public static int findMax( int a[])
  {
    int max = a[0];
    for( int x : a)
      if ( max < x )
        max = x;
    return max;
  }

  public static void main(String args[] )
  {
    int A[] = {1, 8, 7, 56, 90 };

    int max = findMax(A);
    System.out.printf("Maximum value is %d\n", max);

  }
}
   
Comments
Maciej Los 22-Mar-21 4:16am
   
5ed!
CPallini 22-Mar-21 8:06am
   
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900