Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

VI. Writing Methods. Keep it simple 1. Write a method called print that is passe

ID: 3683495 • Letter: V

Question

VI. Writing Methods. Keep it simple

1. Write a method called print that is passed an array of int as a parameter and prints on separate lines the values in that array.

2. Write a method called largest that is passed an array of int as a parameter and returns the largest value in the array.

3. Write a method called total that is passed a one-dimensional array of integers as a parameter and returns the total of the values.

4.1 Write a method isSorted that is passed a one-dimensional array of integers and returns true if the array is already in sorted order and false otherwise.

4.2 Write a variation of the method OrderedLinearSearch that is passed a one-dimensional array of integers and a value that returns the last location of the value in the array, or -1 if the value is not found. The array is in sorted order and can contain duplicates.

Explanation / Answer

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        HelloWorld test=new HelloWorld();
        int n[]={1,2,3,4,5,5,6};
        test.print(n);
        System.out.println("Largest is "+test.largest(n));
       System.out.println("Total is "+ test.total(n));
        System.out.println("Is the array sorted "+ test.isSorted(n));
        System.out.println("Element 6 at found "+ test.OrderedLinearSearch(n,6));
      
     }
     public void print(int[] n)
     {
         for(int i=0;i<n.length;i++)
         System.out.print(n[i]);
     }
     public int largest(int[] n)
     {
         int max=0;
         for(int i=0;i<n.length;i++)
         {
             if(max<n[i])
             max=n[i];
         }
         return max;
     }
     public int total(int[] n)
     {
         int total=0;
         for(int i=0;i<n.length;i++)
         total+=n[i];
         return total;
     }
     public boolean isSorted(int[] n)
     {
         if(n.length==1)
         return true;
         else
         {
             int diff=0;
             if(n[0]-n[1]>0)
             diff=1;
         for(int i=2;i<n.length-1;i++)
            if(n[i] - n[i-1]> diff || n[i]-n[i-1]==0)
            continue;
            else
            return false;
            return true;
         }
     }
     public int OrderedLinearSearch(int[] n,int no)
     {
         int index=-1;
         for(int i=0;i<n.length;i++)
         {
             if(no==n[i])
             index=i;
             else
             if(n[i]>no)
             return -1;

         }
         return index;
     }
}