107k views
23 votes
Write a Java program which declares and populates an array with some values (at least 5 values). Then it should call a method passing it the array. The method should modify the array values using a loop. Lastly, after the program calls the method, it should display the modified array contents to the console.

1 Answer

9 votes

Answer:

CODE IN JAVA :

import java.util.*;

public class Main

{

public static void modifyArray(int[] arr, int n){

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

arr[i] = -1; // each value is modified to -1

}

}

public static void main(String[] args) {

int n;

System.out.print("Enter size of array(atleast 5): ");

Scanner sc = new Scanner(System.in);

n = sc.nextInt();

int array[] = new int[n]; // array with size n declared

// populating the array

System.out.print("Enter array elements: ");

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

array[i] = sc.nextInt();

}

// modifying array via a function

modifyArray(array, n);

// printing array values after modifiction

System.out.print("Array after modification: ");

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

System.out.print(array[i] + " "); // space separated

}

}

}

Step-by-step explanation:

User Bhuvan Bhatt
by
5.4k points