Home > Software engineering >  i have initialized a variable with zero at the top of the function so during a loop the value change
i have initialized a variable with zero at the top of the function so during a loop the value change

Time:01-24

public class maxsubarraysum {

    public static void main(String[] args) {
        int numbers[] = { 1, -2, 6, -1, 3 };
        printmsasum(numbers);
    }

    public static void printmsasum(int numbers[]) {
        int currsum=0;//declared and initialized
        int maxsum = Integer.MIN_VALUE;
        for (int i = 0; i < numbers.length; i  ) {
            int start = i;
            for (int j = i; j < numbers.length; j  ) {
                int end = j;
                 currsum = 0;                    //here is what i dont understand why i have to again give it zero to run it properly what its is called ? means am i missing any concept? pls help in loops does value changes?
                for (int k = start; k <= end; k  ) {
                    currsum  = numbers[k];
                }
                System.out.println(currsum);
                if (maxsum < currsum) {
                    maxsum = currsum;
                }
            }
        }
        System.out.println("the maximum sub array sum is = "   maxsum);
    }

}

i tried it with only declaring and initializing the currsum variable with zero ,then the output is wrong then inside the second nested loop why i have to initialized it with zero for correct answer?

CodePudding user response:

You are declaring cursum in the function so its scope is the entire function, which contain all the loops. It will not be reset to 0 on entering your inner loop as its scope is outside of that loop.

You could just move its declaration inside the second loop, right before your "k" loop. That will restrict its scope to the iteration over k which looks to be the partial sum you want.

That would be replacing your

cursum = 0; 

with

int cursum = 0;

CodePudding user response:

You are changing currsum in every iteration currsum = numbers[k];, so to check every new result, you have to reset the currsum. You don't have to declare it before loops, you can actually declare it in the same place you are setting it to 0.

Tip: You also don't have to initalize start and end variables, you can use i and j

  • Related