Arrays and Its Basics.

Arrays and Its Basics.

What is an Array?

  • Array is one of the most fundamental Data Structure in the world of programming.
  • An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together.
  • This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).
  • Arrays come in multiple Dimensions. In this article, we are only covering 1D array.

objects-tenElementArray.gif

Syntax & In-Built Functions of Array.

  • The general syntax of declaring an array is: (Type of array) (array name) ([Size of array])
    int array1 [10]; //Array declaration in C++
    
    C++ also gives you a super useful in-built function called as sort. As the name suggests, we use sort function to sort the elements of an array. Want to know how? Keep reading till the end.

Time Complexities of an Array.

  • There are 3 major time complexities you must remember about any Data Structure.(Search, Insert, and Delete).
  • Suppose, we have an array of size N. Then,
  • The time complexity of searching an element in array is O(1).
  • The time complexity of inserting an element in array is O(N).
  • The time complexity of deleting an element in array is O(N).

Code Example.

  • Well, we have discussed quite a few things till now. Let's have a look at a code snippet that shows everything that we have discussed till now.
// TC Means Time Complexity.
# include<bits/stdc++.h>
using namespace std;
int main()
{   int n;
    cin>>n;
    int arr[n]; // creating an array of size 3.
    int arr2[3] = {1,3,5}; // another way to initialize an array.
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];    // populating the array with user input
    }
    cout<<"Second Element is: "<<arr[1]<<endl;
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<endl;   // printing all elements. TC of Traversing is O(N)
    }

    sort(arr,arr+n);  // in-built function to sort the array. TC is O(N*Log(N))
}

Conclusion.

Now you have a good understanding of the basics of an array. You have learned;

  • How to create an array
  • How to take user input and access an element of the array
  • How to sort an array.
  • General Time Complexities of an array.

In the next article, we will have a look at vectors.

Did you find this article valuable?

Support CompSciWithIyush by becoming a sponsor. Any amount is appreciated!