Learning Programming #1.5 The Basics: Arrays

Arrays are important constructs in programming, as they allow easy access and storage of multiple(ranging from 0 to whatever number your memory can handle) variables of the same type.

In my last post you learned about functions which allow more readable code and help you avoid redundancy.

When I started my first game I didn't know about arrays. In the following I want to show you what I could have gathered if I was using arrays(on the left you can see an extract of the code of my first game, on the right inside the green box you can see that same extract simplified with arrays):
Untitled.png

Python offers no arrays, but only lists which I will discuss in #1.6. This is better for the inexperienced user, but demonstrates, that python sacrifices a few things for its lack of syntax.
Arrays are able to store a certain amount of variables of any type. The length of an array is defined once upon creation and can never be changed afterwards.
In java there are two ways to create an array:

  1. Create an empty array of defined length and a certain variable type:
    type [] nameOfArray = new type[length];
  2. Create an array and fill it with the specified variables. In The following example I create an int-array of length 5 that will be filled with 1, 6, 274, 95, 0:
    int [] array = new int[5]{1, 6, 274, 95, 0};

Accessing arrays is very easy. You just type the name of the array and specify which position of the array you want to use. You only need to keep in mind that you always need to start counting with 0 not with 1 in programming. Changing the values of arrays is also not very hard:

int [] array = new int[2]{47, 29};
int element1 = array[0];
int element2 = array[1];
array[1] = 2638; // Now the second element of the array is 2638.
array[0] = array[0]-1 // Now the first element of the array is 46.
array = new int[2]{element1, element2}; // Now the array is back to its original state.

You can also use a for loop if need to perform the same calculation on each element of the array. You can such a loop in the image.

Taks

Create an array of length 10000 and fill it with the numbers from 0 to 9999 using a for loop.

Sort:  

Congratulations @quantumdeveloper! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 50 upvotes. Your next target is to reach 100 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

SteemitBoard - Witness Update
SteemitBoard to support the german speaking community meetups
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.36
TRX 0.12
JST 0.040
BTC 70446.49
ETH 3571.68
USDT 1.00
SBD 4.73