Write a method named generateArray that accepts an int size as its parameter and returns an int[] array where each element is populated incrementally beginning at 1 and ending at the size (inclusive).

Example: if the parameter was 5, your method should return an int[] array containing values: {1,2,3,4,5}. Example 2: if the parameter was 9 your method should return an int[] array containing values: {1,2,3,4,5,6,7,8,9}.

Hint - try to populate the array with 0 - size-1 first and then adjust :) *You may assume they will enter a positive number.

Respuesta :

The program illustrates the use of methods and arrays.

  • Arrays are used to hold multiple values using one variable
  • Methods are used to combine blocks of code, where the codes can be called using one name.

The generateArray method, where comments are used to explain each line is as follows:

//This defines the method

public static int[] generateArray (int n)  {  

   //This declares an array of n elements

   int[] arr = new int[n];

   //The following iteration populates the array

   for(int i = 0;i<n;i++){

       arr[i] = i+1;

   }

   //This returns the populated array

   return arr;  

}  

At the end of the generateArray method, the array is returned to the main method

See attachment for sample run

Read more about similar programs at:

https://brainly.com/question/14202696

Ver imagen MrRoyal