ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Data Structures
    CSI-413
    Progress0 / 19 topics
    Topics
    1. Introduction to Data Structures2. Arrays3. Stacks4. Queues5. Priority Queues6. Linked Lists7. Trees8. Graphs9. Recursion10. Sorting Algorithms11. Searching Algorithms12. Hashing13. Storage and Retrieval Properties and Techniques for Data Structures14. Algorithm Complexity15. Polynomial and Intractable Algorithms16. Classes of Efficient Algorithms17. Divide and Conquer18. Dynamic Programming19. Greedy Algorithms
    CSI-413›Arrays
    Data StructuresTopic 2 of 19

    Arrays

    6 minread
    1,082words
    Intermediatelevel

    Arrays in C++

    An array is a collection of elements, all of the same type, stored in contiguous memory locations. It allows you to store multiple items under a single variable name, and each item can be accessed using an index or a subscript.

    Arrays are one of the most fundamental and widely used data structures in C++ and other programming languages. They provide a way to efficiently store and manipulate a large collection of data elements.

    Properties of Arrays

    1. Fixed Size: The size of an array is fixed when it is declared. It cannot be changed during runtime. This means that when you define an array, you must know the number of elements it will hold.

    2. Homogeneous Elements: All elements in an array must be of the same data type. For example, an array can hold only integers, only floating-point numbers, or only characters.

    3. Contiguous Memory Allocation: The elements of an array are stored in consecutive memory locations. This allows efficient indexing and access.

    4. Indexing: Array elements are accessed by an index, starting from 0 (in C++). The first element is accessed using index 0, the second using index 1, and so on.

    Declaring an Array

    In C++, arrays are declared by specifying the type of elements followed by the array name and size (the number of elements).

    Syntax:

    type arrayName[size];
    
    • type: The data type of the elements (e.g., int, float, char).
    • arrayName: The name you choose for the array.
    • size: The number of elements the array can hold (must be a constant or a fixed number).

    Example:

    int arr[5];  // Declares an array of 5 integers
    

    Here, arr can store 5 integer values, indexed from arr[0] to arr[4].

    Initialization of Arrays

    Arrays can be initialized at the time of declaration using curly braces {}.

    • Static Initialization: Elements are assigned values explicitly.

      Example:

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

      In this example, arr[0] is initialized to 1, arr[1] to 2, and so on. If the number of values in the initializer list is less than the array size, the remaining elements are initialized to 0.

    • Partial Initialization: If fewer values are provided than the size of the array, the remaining elements are initialized to 0.

      Example:

      int arr[5] = {1, 2};  // arr[0] = 1, arr[1] = 2, arr[2] = 0, arr[3] = 0, arr[4] = 0
      
    • Dynamic Initialization: Arrays can also be initialized dynamically at runtime, but this requires using pointers and dynamic memory allocation (e.g., new keyword).

      int *arr = new int[5];  // Dynamically allocates an array of 5 integers
      

    Accessing Array Elements

    Array elements are accessed using the array name followed by an index in square brackets.

    • Example:
      int arr[5] = {10, 20, 30, 40, 50};
      cout << arr[0];  // Access the first element (10)
      cout << arr[3];  // Access the fourth element (40)
      

    Remember, array indices in C++ are 0-based, meaning the first element is at index 0, the second at 1, and so on.

    Multidimensional Arrays

    In C++, you can create arrays with more than one dimension (e.g., 2D or 3D arrays).

    • 2D Array Example:

      int arr[3][4];  // A 2D array with 3 rows and 4 columns
      

      To access or initialize a 2D array:

      arr[0][0] = 1;  // Accessing element at the first row, first column
      arr[2][3] = 10; // Accessing element at the third row, fourth column
      

      You can also initialize a 2D array in a similar manner:

      int arr[2][2] = {{1, 2}, {3, 4}};
      
    • 3D Array Example:

      int arr[2][3][4];  // A 3D array with 2 blocks, each containing 3 rows of 4 columns
      

    Array Advantages

    1. Efficient Access: Arrays allow constant-time access to any element via an index (O(1) time complexity), making them fast for lookups and updates.
    2. Contiguous Memory Allocation: Since elements are stored contiguously in memory, array traversal is fast, and caching is more efficient.

    Array Limitations

    1. Fixed Size: The size of the array is fixed at the time of declaration. You cannot change it during runtime, which can be inefficient if the required size is unknown beforehand.
    2. Inefficient Insertions/Deletions: Inserting or deleting elements in the middle of an array is inefficient, as it requires shifting elements to accommodate the change.
    3. Memory Wastage: If the array is too large for the amount of data it holds, memory may be wasted. Conversely, if the array is too small, it may not be able to accommodate all data.

    Common Operations on Arrays

    1. Traversal: Iterating over all the elements of the array using a loop.

      for (int i = 0; i < 5; i++) {
          cout << arr[i] << " ";  // Prints each element of the array
      }
      
    2. Searching: Finding an element in an array. This can be done using linear search or binary search.

      • Linear Search: This approach checks each element sequentially.
        bool found = false;
        for (int i = 0; i < 5; i++) {
            if (arr[i] == 30) {
                found = true;
                break;
            }
        }
        
    3. Sorting: Sorting the array in ascending or descending order. This can be done using sorting algorithms like bubble sort, selection sort, or more advanced ones like quicksort or mergesort.

    4. Reversing: Reversing the order of elements in the array.

      for (int i = 0; i < 5 / 2; i++) {
          int temp = arr[i];
          arr[i] = arr[5 - 1 - i];
          arr[5 - 1 - i] = temp;
      }
      

    Conclusion

    Arrays are an essential data structure in C++ for storing and manipulating a collection of homogeneous elements. While they offer efficient access and fast traversal, their fixed size and lack of flexibility in insertion and deletion can sometimes be limiting. Nonetheless, arrays are commonly used due to their simplicity and performance benefits in many applications. For more dynamic or complex data handling, other data structures like linked lists or dynamic arrays (e.g., std::vector in C++) can be considered.

    Previous topic 1
    Introduction to Data Structures
    Next topic 3
    Stacks

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,082
      Code examples0
      DifficultyIntermediate