C Programming Language Free Course Part-3

78 / 100

C Programming Language Free Course Part-3

C Programming
C Programming

Arrays

Introduction to Arrays

An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow you to store and manipulate large sets of data efficiently using a single variable name.

  • Declaration:
    To declare an array, you specify the data type, array name, and the number of elements.

     

    Example:

    int numbers[10]; // An array of 10 integers
  • Initialization:
    Arrays can be initialized at the time of declaration.

    Example:

    int numbers[5] = {1, 2, 3, 4, 5};
  • Accessing Elements:
    Elements of an array can be accessed using indices, starting from 0.

     

    Example:

    int firstNumber = numbers[0]; // Accessing the first element

Operations on Arrays

  • Traversing:
    Accessing each element of the array sequentially.

    Example:

    for (int i = 0; i < 5; i++) {
            printf("%d ", numbers[i]);
    }
  • Insertion:
    Adding elements at a specific position (usually involves shifting elements).
  • Deletion:
    Removing elements from a specific position (also involves shifting).
  • Updating:
    Modifying the value of elements at a specific index.

Sorting

Sorting is the process of arranging elements in a particular order. Here are three common sorting algorithms:

  1. Selection Sort:
    Repeatedly finding the minimum element from the unsorted part and putting it at the beginning.

    Example:

    void selectionSort(int arr[], int n) {
         for (int i = 0; i < n - 1; i++) {
                 int minIndex = i;
                 for (int j = i + 1; j < n; j++) {
                         if (arr[j] < arr[minIndex]) {
                                 minIndex = j;
                           }
                     }
                   // Swap the found minimum element with the first element
                   int temp = arr[minIndex];
                   arr[minIndex] = arr[i];
                   arr[i] = temp;
            }
    }
  2. Bubble Sort:
    Repeatedly swapping adjacent elements if they are in the wrong order.
    c
    void bubbleSort(int arr[], int n) {
          for (int i = 0; i < n - 1; i++) {
                   for (int j = 0; j < n - i - 1; j++) {
                            if (arr[j] > arr[j + 1]) {
                                    // Swap arr[j] and arr[j+1]
                                    int temp = arr[j];
                                    arr[j] = arr[j + 1];
                                    arr[j + 1] = temp;
                             }
                         }
                     }
                 }
  3. Insertion Sort:
    Building a sorted array one element at a time by repeatedly inserting elements into their correct position.

    Example:

    void insertionSort(int arr[], int n) {
           for (int i = 1; i < n; i++) {
                  int key = arr[i];
                  int j = i - 1;
                  while (j >= 0 && arr[j] > key) {
                          arr[j + 1] = arr[j];
                        j--;
               }
              arr[j + 1] = key;
       }
    }

Searching

Searching is the process of finding the location of a given element within an array.

  1. Linear Search:
    Checks each element of the array one by one until the desired element is found or the array ends.

    Example:

    int linearSearch(int arr[], int n, int x) {
           for (int i = 0; i < n; i++) {
                  if (arr[i] == x) {
                          return i; // Return the index of the element
          }
        }
           return -1; // Element not found
    }
  2. Binary Search:
    Requires the array to be sorted. It divides the array into halves to find the element efficiently.

    Example:

    int binarySearch(int arr[], int n, int x) {
           int left = 0, right = n - 1;
            while (left <= right) {
                   int mid = left + (right - left) / 2;
                   if (arr[mid] == x) {
                        return mid; // Element found
    } else if (arr[mid] < x) {
          left = mid + 1;
    } else {
          right = mid - 1;
    }
    }
    return -1; // Element not found
    }

Multidimensional Arrays

  • Definition:
    Multidimensional arrays are arrays of arrays. The most common is a two-dimensional array, which can be thought of as a matrix or a table.
  • Declaration:
    int matrix[3][3]; // A 3x3 matrix
  • Initialization:
    int matrix[2][2] = {{1, 2}, {3, 4}};
  • Accessing Elements:
    int element = matrix[0][1]; // Accessing the element in the first row, second column

Pointers and Arrays

Pointers and arrays have a close relationship in C, as the name of an array is a pointer to its first element.

  • Pointer to Array:

    Example:

    int arr[5] = {1, 2, 3, 4, 5};
    int *ptr = arr; // Pointer to the first element of the array
  • Accessing Array Elements Using Pointers:

    Example:

    for (int i = 0; i < 5; i++) {
    printf("%d ", *(ptr + i)); // Accessing elements using pointer arithmetic
    }

Pointer and 2-D Arrays

  • Pointer to 2-D Array:
    A 2-D array can be accessed using pointers by first pointing to the array’s row

    Example:

    .int matrix[3][3];

    int (*ptr)[3] = matrix; // Pointer to an array of 3 integers
  • Accessing Elements Using Pointers:
    for (int i = 0; i < 3; i++) {
           for (int j = 0; j < 3; j++) {
                    printf("%d ", *(*(ptr + i) + j));
            }
    printf("\n");
    }

Array of Pointers

An array of pointers can store addresses of different data types or strings.

Example:

char *names[] = {"Alice", "Bob", "Charlie"};
printf("%s", names[0]); // Accessing the first string

Dynamic Memory Allocation

Dynamic memory allocation allows you to allocate memory during runtime using functions from <stdlib.h>.

  • Functions:
    • malloc(): Allocates memory but does not initialize it.
    • calloc(): Allocates and initializes memory to zero.
    • realloc(): Resizes previously allocated memory.
    • free(): Frees allocated memory.

Example:

int *arr;
arr = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers
if (arr != NULL) {
      // Use the allocated memory
      for (int i = 0; i < 5; i++) {
                arr[i] = i;
     }
// Free the allocated memory
free(arr);
}

Structures

Structure Declaration

A structure is a user-defined data type that allows you to group different types of variables under one name.

Example:

struct Person {
        char name[50];
         int age;
          float height;
};

Operations on Structures

  • Creating Structure Variables:
    struct Person person1;
  • Accessing Members:
    person1.age = 30;
    strcpy(person1.name, "John");
  • Initialization:
    struct Person person2 = {"Alice", 25, 5.5};

Nesting of Structures

You can nest one structure within another to create complex data models.

struct Address {
        char city[50];
        int zip;
};

struct Employee {

              char name[50];
              struct Address address; // Nested structure
};

Array of Structures

An array of structures allows you to store multiple records of the same type.

struct Person people[3];
people[0].age = 20;

Difference Between Arrays and Structures

  • Arrays:
    • Store elements of the same data type.
    • Elements are accessed using indices.
    • Fixed size once declared.
  • Structures:
    • Store elements of different data types.
    • Members are accessed using the dot (.) operator.
    • Size depends on the combined size of all members.

Passing Structures to Functions

Structures can be passed to functions by value or by reference (using pointers).

  • By Value:
    void printPerson(struct Person p) {
    printf

Read more- C Programming Language Free Course

Read more-C Programming Language Free Course Part-2

WhatsAppEmailGmailCopy LinkXWordPressAmazon Wish ListLinkedInFacebookSnapchatSlashdotTelegramViberYahoo MailTrelloTwitterMessengerBlogger

Leave a comment

Exit mobile version