Tuesday, August 5, 2025

Working with Arrays for BCA Semester 1 or IT Students

Prepared By : Prof. Uday Shah


Working with Arrays


Introduction About an Array

  • An array is a collection of elements of the same data type stored in contiguous memory locations.

  • Arrays allow multiple values to be stored using a single variable name.

  • The elements are accessed using an index, starting from 0.

  • Arrays simplify handling large sets of data efficiently.

  • They are especially useful when dealing with lists, sequences, and tabular data.

  • Arrays are static in size; their length must be declared at compile time.

  • All elements in an array must be of the same data type (e.g., all int, float, char).

  • They can be single-dimensional or multi-dimensional.

  • Arrays are stored in contiguous memory which allows fast access using index arithmetic.

  • They are essential for iterative operations where similar data items need to be processed.

  • Arrays can be passed to functions for modular coding.

  • Limitations include fixed size and lack of built-in boundary checking.


Declaration and Initialization of an Array

  • Declaration specifies the type and size of the array.

  • Syntax: data_type array_name[size]; e.g., int numbers[10];

  • Initialization assigns initial values to the array elements.

  • Arrays can be initialized at the time of declaration or separately.

  • Example: int arr[5] = {10, 20, 30, 40, 50};

  • If fewer initial values are given, remaining elements are initialized to zero.

  • Arrays can also be initialized element by element: arr[0] = 5;

  • The size can be omitted during declaration if initialized immediately.

  • Compiler allocates contiguous memory based on declared size.

  • Character arrays can be initialized as strings using double quotes.

  • Proper initialization avoids garbage values.

  • Array elements can be initialized dynamically using loops or user input.


Accessing Array Elements

  • Array elements are accessed using their index positions.

  • Syntax: array_name[index] e.g., numbers[2]

  • Indexing starts from 0 up to size-1.

  • Looping structures like for and while are commonly used for accessing elements.

  • Example:

    for(int i = 0; i < size; i++)  
        printf("%d", arr[i]);  
    
  • Incorrect index access can cause runtime errors.

  • Multi-dimensional arrays require multiple indices (e.g., arr[2][3]).

  • Elements can be read from user input or assigned in code.

  • Arrays passed to functions are accessed similarly inside the function.

  • Efficient access allows for operations like search, sort, and traversal.

  • Pointer arithmetic can also be used for element access.

  • No automatic bounds-checking is done by the compiler in C.


Types of an Array

One Dimensional Array

  • Also called Linear Array or Vector.

  • Consists of a single row of elements.

  • Syntax: int arr[5];

  • Accessed using a single index.

  • Commonly used for lists and sequences.

  • Operations: traversing, searching, sorting, etc.

  • Simplest form of an array.

  • Stored in continuous memory blocks.

  • Efficient for operations on single-row data.

  • Limited in representing tabular data.

  • Array size is fixed at declaration.

  • Array is passed as a pointer when used in functions.

Two Dimensional Array

  • Represents a table (matrix) with rows and columns.

  • Syntax: int arr[3][4]; (3 rows, 4 columns).

  • Accessed using two indices: arr[row][column].

  • Used for applications like matrices, tables, and grids.

  • Nested loops are used to traverse 2D arrays.

  • Memory is still linear, but logically treated as 2D.

  • Example:

    for(i=0;i<rows;i++)
      { 
           for(j=0;j<cols;j++)  
          {  
              printf("%d", arr[i][j]);  
           }
     }

  • Supports arithmetic and logical operations on tabular data.
  • Initialization can be done with nested braces.

  • Ideal for programs involving complex data tables.

  • Data is stored in row-major order by default.

Multi Dimensional Array

  • Arrays with more than two dimensions.

  • Syntax: int arr[2][3][4]; (3D array example).

  • Can be visualized as an array of arrays of arrays.

  • Used in applications like 3D graphics, simulations, and data cubes.

  • Accessed using multiple indices.

  • Initialization becomes complex with more dimensions.

  • Loops for accessing are nested accordingly.

  • Memory consumption increases with each added dimension.

  • Limited practical use beyond 3 or 4 dimensions.

  • Requires a good understanding of memory layout.

  • Performance can degrade with very large multidimensional arrays.

Character Array (String)

  • A one-dimensional array of characters ending with a null character \0.

  • Syntax: char str[10]; or char str[] = "Hello";

  • Used to store and manipulate text data.

  • Handled using string library functions like strcpy, strlen, etc.

  • Elements accessed using index or string functions.

  • Null terminator is mandatory to mark the end of string.

  • Can be read using gets, scanf, or fgets.

  • Supports string concatenation, comparison, search operations.

  • String arrays can be passed to functions as character pointers.

  • Important for text-based applications.

  • Must handle memory carefully to avoid overflow.

Array with Functions Using UDF (User Defined Functions)

  • Arrays can be passed to functions for modular operations.

  • Arrays are passed by reference (only address passed).

  • Syntax: void display(int arr[], int size);

  • Functions can modify array elements.

  • Used for tasks like searching, sorting, reversing.

  • Function parameters specify data type and size.

  • Passing arrays makes code reusable and modular.

  • Helps in large-scale applications where arrays are processed in multiple functions.

  • Can be combined with recursion for complex tasks.

  • Reduces code redundancy.

  • Enhances program readability and maintenance.


Working with Structure

Introduction to Structure

  • Structure is a user-defined data type to group related variables of different types.

  • Syntax:

    struct Student {  
        int id;  
        char name[20];  
        float marks;  
    };  
    
  • Helps in representing real-world entities.

  • Unlike arrays, structures can have heterogeneous data types.

  • Structure members are accessed using dot operator.

  • Structures occupy contiguous memory for their members.

  • Structures are essential for data management in large programs.

  • Arrays can be included within structures.

  • They are foundational for complex data models.

  • Structures help in file handling and database-like operations.

  • Structures can be nested or passed to functions.

  • Pointer to structures enables dynamic access to data.

Declaration and Initialization of Structure

  • Declaration defines structure layout.

  • Initialization assigns values to structure members.

  • Syntax:

    struct Student s1 = {1, "John", 85.5};  
    
  • Members can also be initialized individually.

  • Arrays within structures are initialized like regular arrays.

  • Structures can be declared globally or locally.

  • Nested structures require hierarchical initialization.

  • Helps in creating organized and readable code.

  • Care must be taken to match data types during initialization.

  • Structure variables can be declared with or without typedef.

Nested Structure

  • Structures that contain another structure as a member.

  • Useful for representing hierarchical or composite data.

  • Syntax:

    struct Date { int day, month, year; };  
    struct Student { int id; struct Date dob; };  
    
  • Accessed using multiple dot operators (e.g., s1.dob.day).

  • Nested structures enhance modular data organization.

  • They reduce code redundancy.

  • Useful for complex records like employee details, student data, etc.

  • Can also be combined with arrays for multidimensional data.

  • Nested structures increase code readability and maintainability.

  • Memory is allocated in a nested manner.

Array within Structure

  • Structures can have arrays as members.

  • Example:

    struct Student { char name[30]; int marks[5]; };  
    
  • Arrays help in grouping similar data within a structure.

  • Useful for handling batch data like multiple subject marks.

  • Elements are accessed using structure variable and index.

  • Loops are used to process array members inside structures.

  • Makes data handling efficient and organized.

  • Helps in applications like managing scores, inventories, etc.

  • Increases memory size of the structure accordingly.

  • Ensures related data stays together logically.

Array of Structure

  • Declaring an array where each element is a structure.

  • Syntax: struct Student s[50];

  • Used to manage multiple records (like list of students).

  • Accessed using index and dot operator: s[0].id = 101;

  • Arrays of structures are essential in database applications.

  • Supports batch processing of complex records.

  • Can be passed to functions for manipulation.

  • Allows efficient storage and retrieval of related data.

  • Sorting and searching can be implemented over the array.

  • Enhances code structure and readability.

Passing Structure to UDF (User Defined Functions)

  • Structures can be passed to functions by value or by reference.

  • Syntax: void display(struct Student s);

  • Pass by reference using pointers saves memory.

  • Functions can manipulate structure data.

  • Helps in modular and reusable code design.

  • Essential for managing large structured data.

  • Supports operations like display, edit, sort on structure records.

  • Structures can also be returned from functions.

  • Improves data encapsulation.

  • Reduces code duplication and increases flexibility.


:: Best Of Luck ::