Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I index the array to start as 1 rather than 0?

In this case the program is supposed to add all the arrays together. However if I entered 1 in the sum method parameter it would start counting from 7 onwards but if I put 0 it outputs 0.

public class sList {

   public static void main(String[]args) {
       int[] array = {10,7,11,5,13,8}; // How do I make it read the value 10 as 1 in the array?
       sum(array.length,array);
   }

   public static int sum(int n, int[] S) {
       int i;
       int result;

       result = 0;
       for(i=1;i<=n;i++)
           result = result + S[i];

       System.out.println(result);
       return result;
   }    
}
like image 844
user1883386 Avatar asked Dec 27 '22 12:12

user1883386


1 Answers

I wouldn't pass the length in, because:

  • it's redundant - array.length tells you the length if you want to know it
  • you don't need to know the length anyway, because there's a better way to iterate over an array

Instead, just iterate through the whole array passed in using a foreach loop:

public static int sum(int[] array) {
    int result = 0;
    for (int i : array)
        result += i;
    return result;
}

Doing this results in a lot less code, which in turn is easier to read and understand.

like image 143
Bohemian Avatar answered Jan 08 '23 16:01

Bohemian