logo

Предаване на масив към функция в Java

Функциите се използват за разбиване и разделяне на огромен код на малки части, така че кодът да стане по-разбираем и по този начин да се намали сложността на кода. Масивите са хомогенни структури от данни за намаляване на сложността на кода, повишаване на ефективността и намаляване на времето за изпълнение на кода. Ние използваме масива и мислим, че и двете тези спестяващи време части от програмирането се изпълняват заедно. По този начин съществува концепцията за преминаване Масив да функционира.

В този раздел ще научим как можем да предадем масив към дефинирана от потребителя функция и ще забележим как това прави кода по-оптимистичен, както и ефективен.

Като цяло, целта на предаването на масив към функция е да се прехвърли голямо количество данни между методите. За да предадете масив към функция, просто предайте масива като параметър на функцията (като нормални променливи) и когато предадем масив към функция като аргумент, всъщност се предава адресът на масива в паметта, което е справка. По този начин всички промени в масива в рамките на метода ще повлияят на действителните стойности на масива.

Ще имплементираме някои примерни кодове, чрез които ще научим как да предадем масив към функция.

Пример 1:

Изчисляване на максималните и минималните стойности на даден масив.

За да получим максималната и минималната стойност в масив, можем да изпълним показания по-долу код:

 import java.util.Scanner; public class array { public int max(int [] array) { int max = 0; for(int i=0; imax) { max = array[i]; } } return max; } public int min(int [] array) { int min = array[0]; for(int i = 0; i <array.length; i++ ) { if(array[i]<min) min="array[i];" } return min; public static void main(string args[]) scanner sc="new" scanner(system.in); system.out.println('enter the array range'); int size="sc.nextInt();" int[] arr="new" int[size]; elements of ::'); for(int i="0;" i<size; i++) arr[i]="sc.nextInt();" m="new" array(); system.out.println('maximum value in is::'+m.max(arr)); system.out.println('minimum is::'+m.min(arr)); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/73/passing-array-function-java.webp" alt="Passing Array to Function In Java"> <p> <strong>Code Explanation:</strong> </p> <ul> <li>In the above code, we created a class <strong>array</strong> within which we have created a <strong>max()</strong> function and <strong>min()</strong> </li> <li>In the <strong>max ()</strong> function, we have passed an array as the function parameter, and using for loop, we found the maximum value in the array by indexing i from 0 to the length of the array, and as soon it finds the maximum value, it gets stored in the max variable. The condition is that if any of the elements present in the array is greater than the max variable (i.e., max=0 initially), then only it will assign that maximum value to the array.</li> <li>Next, in the min () function, we performed the same, but in this, we have found the minimum value present in the array.</li> <li>Finally, in the main () method, we printed the obtained max and min values from the array.</li> </ul> <h3>Example 2:</h3> <p> <strong>Computing an array of Random Numbers</strong> </p> <p>Random numbers are those numbers whose occurrence is random and cannot be predicted reasonably.</p> <p>Below is the example code through which we can understand the passing of an array to a function and generate random numbers:</p> <pre> public class array { public static void main(String[] args) { final int n = 6; int[] random_array; random_array = create_random(n); System.out.println(&apos;The array of random numbers is:&apos;); for (int i = 0; i <random_array.length; i++) { system.out.print(random_array[i] + ' '); } public static int[] create_random(int n) random_array="new" int[n]; for (int i="0;" <random_array.length; random_array[i]="(int)" (math.random() * 10); return random_array; < pre> <p> <strong>On executing the code, we got the below-shown output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/73/passing-array-function-java-2.webp" alt="Passing Array to Function In Java"> <h4>Note: In the case of random numbers, always the result will vary as the numbers are generated randomly.</h4> <h3>Example 3:</h3> <p> <strong>Sorting numbers of an array</strong> </p> <p>Below is an example code where we pass an array to a function and sort the elements of the given array:</p> <pre> class array { public static void main(String[] args) { int[] n={12,24,2,89,34,45}; System.out.println(&apos;Before sorting&apos;); display(n); sort(n); System.out.println(&apos;
 After Sorting :&apos;); display(n); } static void display(int n[]) { for(int i=0; i<n.length;i++) system.out.print(n[i] + ' '); } static void sort(int n[]) { int i, j, temp; for(i="0;" i<n.length-i;i++) for(j="0;" jn[j+1]) temp="n[j];" n[j]="n[j+1];" n[j+1]="temp;" < pre> <p> <strong>When we executed the above code, we got the following result:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/73/passing-array-function-java-3.webp" alt="Passing Array to Function In Java"> <p>These are some of the possible example implementations through which it is understandable that how one can pass an array to a function in Java.</p> <hr></n.length;i++)></pre></random_array.length;></pre></array.length;>