Home > Blockchain >  Why won`t this simple function output anything if I don`t use a break statement?
Why won`t this simple function output anything if I don`t use a break statement?

Time:07-09

Function here is , implemented to find the largest number in an array .. if I don't put a break statement after while , it won't print out anything . I need someone to explain me how this code works . What I was thinking is that ,

1- we go into first loop , and then the second loop.. 2- we have the first and second elements compared in the while loop . 3- if condition is true , int largest is set to the large value.. 4- and then we go back to the outer for loop again .

Isn't this true ? aren't we going back to the outer for loop after while statement is issued once ? If I don't put a break , while condition is true , the program won't come out of the loop , is that so ?

I`m testing the code in main , by calling this function and passing in an integer array . I forgot to mention this before . Sorry .

Thank you .

public int returnMax(int[] nums) {
    int largest = 0;
    for (int i = 0; i < nums.length; i  ) {
        for (int j = 1; j < nums.length; j  ) {
            while (nums[j] > nums[i]) {
                largest = nums[j];
                break;
                
            }

        }
    }
    return largest;

}

CodePudding user response:

if nums[j] is larger than nums[i] it goes into your while loop. In your while loop you never change any variable except for largest. Largest is never used except for returning a value. This causes an infinite loop because the next iteration your while expression is the still the same.

CodePudding user response:

The program can't leave the while statement, because the condition is never changes and is always true (once it's true). You should replace the while with an if.

if (nums[j] > nums[i]) {
    largest = nums[j];
    System.out.println(largest);
}

Also you out commented System.out.println(largest);, so it will never be called

CodePudding user response:

The first time your code gets to the while loop, j = 1 and i = 0, which means that j is greater than i. These numbers don't change inside this loop. Thus, the loop will never end and the code won't proceed.

You don't need 3 loops for this simple operation. Try the below.

public static int returnMax(int[] nums) {
        int largest = nums[0];
        for (int i = 1; i < nums.length; i  ) {
            if (largest < nums[i]) {
                largest = nums[i];
            }
        }
        return largest;
    }

Kind Regards

  •  Tags:  
  • java
  • Related