HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Write a function named isSuper that returns 1 if its array argument is a isSuper array, otherwise it returns 0

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
argumentarrayfunctionwritenameditsthatissuperreturnsotherwise

Problem

An Super array is defined to be an array in which each element is greater than sum of all elements before that.
 
For example:

  • {2, 3, 6, 13} is a Super array. (2



  • {2, 3, 5, 11} is a NOT a Super array. 2 + 3



I wrote following code to find the array is Super Array or not .

public class SuperArray {
    public static void main(String args[]) {
         System.out.println("The result is: " + isSupper(new int[] {2, 3, 6, 13}));
         System.out.println("The result is: " + isSupper(new int[] {2, 3, 5, 11}));
    }
    public static int isSupper(int[] a){
        int result = 0;
        int sum = 0;
        int nextValue = 0;
        for(int i = 0; i  sum) {   
                result = 1;
            } else {
                result = 0;
                break;
            }
            System.out.println("sum is: " + sum);
            System.out.println("next Value is: " + nextValue);
            sum += a[i];       
        }
        return result;
    }
}


Is this a good way to find Super array? First a assign sum = 0 and check that sum to first number of an array and so on.

Solution

It's easier to use the enhanced for loop like this:

for(int value : a) {
        if(value <= sum) 
            return 0;
        sum += value;       
    }
    return 1;


This also clears up some unnecessary lines like checking if the function should break and return. When you return a value, it immediately leaves the function. Therefore, you don't need to break then return. If all value pass the for loop, then it will return 1.

Also, you might want to return boolean instead of int in your method because it's just true or false.

Code Snippets

for(int value : a) {
        if(value <= sum) 
            return 0;
        sum += value;       
    }
    return 1;

Context

StackExchange Code Review Q#117174, answer score: 7

Revisions (0)

No revisions yet.