Zig Zag Sequence

  • + 15 comments

    Here is a simple solution I came up with.


    static int simpleArraySum(int n, int[] ar) {
    
        int sum = 0;
    
        for(int count = 0; count < ar.length; count++) {
            sum = sum + ar[count];
        }
    
        return sum;
    
    }
    

    Steps:
    1.) You declare a variable to hold the sum.
    2.) Give that variable an initial value.
    3.) Now do a for loop to pass through every single element in the array.
    4.) The first statement in the for loop sets an initial value to its variable count (can be named anything), int count = 0. The second piece of code (count < ar.length) sets a condition for which the loop will continue to run through the array, in this case, it will run until the end of the array. The third piece of code (count++) will add one to the counter which is the code that makes the counter pass through the array by increments of one (step by step).
    5.) The code inside the brackets {sum = sum + ar[count]} will take the initial value of sum and add all of the values found inside the array to it.
    6.) Finally the return statement will simply print out the new values of sum given by the for loop.
    
    *I hope this helps everyone, let me know if it does!