Introduction to Arrays in DSA

Sep 11, 2024

DSA Series - Chapter on Arrays

Introduction

  • Welcome to the Complete DSA Series.
  • Today’s chapter focuses on Arrays.
  • Arrays are the first data structure we will study.

Data Structures and Algorithms

  • Data Structures:

    • Structures in programming used to store data.
    • Essential for building real-life systems (websites, apps, software).
    • Data is the fuel for development and programming.
  • Algorithms:

    • Efficient operations performed on data.
    • Examples include searching and sorting data in data structures.

What is an Array?

  • Arrays help store multiple variables of the same type in a single structure.
  • Example: Storing marks of multiple students.
    • Instead of creating multiple variables (e.g., mark1, mark2, etc.), an array can hold all values together.
    • An array can be visualized as a block of data.

Properties of Arrays

  • Can store the same type of data (e.g., all integers).
  • Data stored contiguously in memory.
  • Arrays are linear structures, meaning data is arranged in a line.

Creating an Array

  • Syntax for creating an array:
    int marks[5];  
    
  • To initialize an array with values:
    int marks[] = {99, 100, 54, 36, 88};  
    
  • Array size can be determined using the sizeof operator.

Accessing Array Data

  • Access array elements using indices.
  • Indices start from 0 to size-1.
  • Example: marks[0] gives access to the first element.

Looping through Arrays

  • Use loops for operations on arrays.
  • Example: Printing elements using a for loop:
    for (int i = 0; i < size; i++) {  
        cout << marks[i];  
    }  
    

Finding Minimum and Maximum

  • To find min/max in an array, iterate through each element and compare.

Linear Search Algorithm

  • A method to find a target value in an array by checking each element sequentially.
  • Returns the index of the found element or -1 if not found.
  • Time complexity: O(n)

Reversing an Array

  • Reverse the order of elements using the two-pointer approach.
  • Swap elements from the front and back until the pointers meet.

Homework Problems

  1. Write a function to calculate the sum and product of all numbers in an array.
  2. Write a function to swap the maximum and minimum numbers of an array.
  3. Write a function to print all unique values in an array.
  4. Write a function to print the intersection of two arrays.

Conclusion

  • Understanding arrays is fundamental in DSA.
  • Next chapter will cover vectors, which are similar to arrays but with additional features.
  • The journey of learning data structures and algorithms has begun.