would this be the correct way to store the index number of an array to the array.

a[b]=a.length;

im not too sure if this is correct. if not please tell me how to do it

Tagged:

Answers

  • Answer ✓

    Think of an array like a shopping list.

    things_to_buy
    ---
    0) Apples
    1) Bananas
    2) Milk
    3) Cheese
    

    What's the length of this list? Well, it's four. There are four things on the list. What's the first (0th) thing on the list? It's Apples.

    Here's a list of numbers:

    nums
    ---
    0) 37
    1) 26
    2) 62820
    

    You might declare this list like this:

    int[] nums = { 37, 26, 62820 };
    

    But you might not know what numbers are in the list when you declare it - you might only know the length.

    int more_nums = new int[100];
    

    So now if you want to assign each number in that list to the index of that number's position, you would use a loop:

    for( int i = 0; i < more_nums.length; i++){
      more_nums[i] = i;
    }
    

    You can see that this loop starts with the first (0th) number in the list, and assigns it the value of 0. Then it goes to the second number (at index 1), and assigns it the value 1. And so on, up to the 99th index. Notice that more_nums[100] is not on the list!

    more_nums
    ---
    0) 0
    1) 1
    2) 2
    ...
    99) 99
    
  • edited January 2018 Answer ✓

    in this expression: a[b]

    • a is the array and
    • b is the index.

    To store the index number of an array just say int b=3;

    Then use b as the index for the array: println(a[b]);

    a.length is the length of the array.

    When you think of the array as an shopping list,

    • a would be the list and
    • b the line number and
    • a[b] the content of that line.

    See tutorial:

    https://www.processing.org/tutorials/arrays/

    Full working sketch:

    int[] nums = { 37, 26, 62820, 223, 12, 66 };
    
    println (nums.length); 
    
    int b = 3; // b is the index (counting starts at 0)
    println (nums[b]);   
    
    
    println("=======================");
    println("Entire array: ");
    printArray (nums);
    println("=======================");
    
    for ( int i = 0; i < nums.length; i++) {  // doing something with the array
      print ( nums[i] * 3 + ",");
    } // end of for-loop
    

    Or with an array of String

    String[] nums = { "Milk", "Butter", "Honey", "Chocolate" };
    
    println (nums.length); 
    
    int b = 3; // b is the index (counting starts at 0)
    println (nums[b]);   
    
    
    println("=======================");
    println("Entire array: ");
    printArray (nums);
    println("=======================");
    
    for ( int i = 0; i < nums.length; i++) { // doing something with the array
      print ( nums[i]  + ",");
    } // end of for-loop
    
Sign In or Register to comment.