0

when I call function by passing array as an argument and we didn't returning something and how will the original array is being changed when i was calling function and after that i was printing the array and in another program i was printing while calling the function it doesn't, i had two code samples the one where it is changing and another is showing error that cannot resolve method println(void).

1st

public static void main(String[] args) {
        int[] arr = {-43,45,-87,-24,10};
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    static void bubbleSort(int[] nums){
        boolean swapped = false;
        // runs n-1 times
        for (int i = 0; i < nums.length; i++) {
            // for each step, max item will come at the last respective index
            for (int j = 1; j < nums.length - i; j++) {
                // swap the item if it is smaller than previous item
                if(nums[j] < nums[j-1]){
                    //swap
                    int temp = nums[j];
                    nums[j] = nums[j-1];
                    nums[j-1] = temp;
                    swapped = true;
                }
            }
          if(!swapped)
                break;
        }
        
    }

2nd

public static void main(String[] args) {
        int[] a = {7,5,4,6,78,34,6};
        System.out.println(ceiling(a));
    }

    static void ceiling(int[] target) {
        int temp=0;
        target[3] = temp;
        target[3] = target[2];
        target[2] = temp;
    }
  • 1
    What is being or should be returned? Can you be more clear? – imraklr Oct 01 '22 at 10:39
  • means we didn't returning anything and how the values inside the array is being manipulated? – Hemant Maurya Oct 01 '22 at 11:00
  • you can refer to [this](https://stackoverflow.com/q/40480/10671013). I believe you are talking about pass by reference/value for the first part (array passed as arg but not returning anything) – Tan Yu Hau Sean Oct 01 '22 at 11:18
  • In the 2nd sample code provided, the statement ```System.out.println(ceiling(a));``` will give an error - ```error: 'void' type not allowed here```. Since ceiling function has ```void``` return type then how can it return anything. Please correct your code. And about that array manipulation, this answer will help you - https://stackoverflow.com/a/12757868/14105067 – imraklr Oct 01 '22 at 11:20

0 Answers0