Write a method with the signature "boolean[] createAlternating(int length)" that takes an integer representing the size of an array, and then returns a new boolean array of that size where each index alternates between true and false (e.g., index 0 is true, index 1 is false, index 2 is true, and so on).

Respuesta :

Answer:

// program in java.

import java.util.*;

// class definition

class Main

{

// mthod that fill the array with true and false

 public static  boolean [] createAlternating(int length)

{

// create array

   boolean arr[]=new boolean[length];

// fill the array

   for(int a=0;a<length;a++)

   {

       if(a%2==0)

       arr[a]=true;

       else

       arr[a]=false;

   }

// return array

   return arr;

}

// main method

public static void main (String[] args) throws java.lang.Exception

{

   try{

// scanner object to read input

Scanner scr=new Scanner(System.in);

System.out.print("Enter the size: ");

// read the size

int n=scr.nextInt();

// store the array

 boolean  []copy = createAlternating(n);

// print the array elements

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

 System.out.print(copy[i]+" ");

   }catch(Exception ex){

       return;}

}

}

Explanation:

Read the size of array from user with Scanner object.call the method createAlternating() with parameter length.Then create an array of size length.Fill the array true at even index and false at odd index.return the array and print the elements.

Output:

Enter the size: 10

true false true false true false true false true false

ACCESS MORE
EDU ACCESS