Revise 1-D Arrays in 2 mins

Revise 1-D Arrays in 2 mins

Brushing up the concepts learnt.

·

2 min read

An array is a Data Structure that can store data types both primitive and complex.

SYNTAX:

The fundamental grasp of the syntax will be in java, but you'll be able to compare it to the language you're already familiar with.

datatype[] variable_name = new datatype{size];

Example:

int num; //declaration, num is getting defined in the stack memory

num = new int[5]; 

//initialization,the object is being created in the heap.

//or simply

int num[] = {1,2,3,4,5};

image.png

**IMPORTANT THINGS TO NOTE: **

  • Arrays may or may not be contiguously stored in the memory ( contiguous means that the objects at different indices are stored in consecutive blocks of memory), it depends on the programming language that you are working with.

  • For an integer array, all values will be zero by default. Printing an empty array will output 0.

  • For a string array, the default value will be NULL.

  • Inserting an element in the array takes O(n) time in the worst case.

  • Every object in the array is stored separately in the array along with the array itself.

image.png

ENHANCED FOR LOOP FOR ARRAYS:

Let's look at the syntax first.

for(int element : array_name){
     print(element);
}

Here, "element" is a variable which is assigned to objects at different indices of the array. It will traverse the array from the first to the last element.

To make it easier, read the for-each loop like this :

for every "element" in the "array_name" print that "element".

Another example might help:

int[] numbers = {3, 4, 5, -5, 0, 12};
   int sum = 0;

   // iterating through each element of the array 
   for (int number: numbers) {
     sum += number;
   }

And that's all. Array as a topic is not that difficult but its applications are vast and somewhat complicated. I am also solving more and more questions related to arrays right now to make the concepts more concrete.

I hope this helped you and if it did make sure to let me know.