ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Passing Arrays Sorting…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    9 min read
    Topic 19 of 39
    Topic Study Note Illustration
    19

    Passing Arrays to Function, Sorting and Searching Arrays

    In C programming, arrays are fundamental data structures, and understanding how to pass arrays to functions, as well as how to sort and search arrays, is crucial...

    Passing Arrays to Function, Sorting and Searching Arrays in C

    In C programming, arrays are fundamental data structures, and understanding how to pass arrays to functions, as well as how to sort and search arrays, is crucial for building efficient and effective programs. Let’s break down these concepts:


    1. Passing Arrays to Functions in C

    In C, arrays can be passed to functions in two ways: by reference and by pointer. When passing arrays to functions, the array's name is treated as a pointer to the first element of the array. This means that when you pass an array to a function, you're actually passing the address of the first element, and the function can modify the array's elements.

    Syntax for Passing an Array to a Function:

    void functionName(type arrayName[], int size) {
        // Function code
    }
    

    Alternatively, you can also pass the array using pointers:

    void functionName(type *arrayName, int size) {
        // Function code
    }
    

    In both cases, the array is passed by reference (using the array's memory address), so modifications inside the function will affect the original array.

    Example: Passing an Array to a Function

    #include <stdio.h>
    
    void printArray(int arr[], int size) {
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }
        printf("\n");
    }
    
    int main() {
        int numbers[] = {5, 10, 15, 20, 25};
        int size = sizeof(numbers) / sizeof(numbers[0]);
    
        printArray(numbers, size);  // Passing array to function
    
        return 0;
    }
    

    Explanation:

    • The function printArray takes an array arr[] and its size as parameters.
    • The array numbers is passed to printArray in the main function.
    • The function prints the array elements.

    Output:

    5 10 15 20 25
    

    2. Sorting Arrays in C

    Sorting an array means arranging its elements in a specific order, either in ascending or descending order. There are several algorithms to sort an array, with Bubble Sort and Selection Sort being two of the simplest.

    Bubble Sort Algorithm:

    Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

    Bubble Sort works by "bubbling" the largest element to the end of the array after each pass.

    Example: Sorting an Array Using Bubble Sort

    #include <stdio.h>
    
    void bubbleSort(int arr[], int size) {
        for (int i = 0; i < size - 1; i++) {
            for (int j = 0; j < size - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap the elements
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    
    void printArray(int arr[], int size) {
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }
        printf("\n");
    }
    
    int main() {
        int numbers[] = {64, 34, 25, 12, 22, 11, 90};
        int size = sizeof(numbers) / sizeof(numbers[0]);
    
        printf("Unsorted array: \n");
        printArray(numbers, size);
    
        bubbleSort(numbers, size);  // Sorting the array
    
        printf("Sorted array: \n");
        printArray(numbers, size);
    
        return 0;
    }
    

    Explanation:

    • The function bubbleSort performs the sorting by comparing adjacent elements and swapping them if they are in the wrong order.
    • The printArray function prints the array before and after sorting.

    Output:

    Unsorted array: 
    64 34 25 12 22 11 90 
    Sorted array: 
    11 12 22 25 34 64 90 
    

    Selection Sort Algorithm:

    Selection Sort works by selecting the smallest (or largest) element from the unsorted part of the array and swapping it with the first unsorted element.

    Example: Sorting an Array Using Selection Sort

    #include <stdio.h>
    
    void selectionSort(int arr[], int size) {
        for (int i = 0; i < size - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < size; 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;
        }
    }
    
    void printArray(int arr[], int size) {
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }
        printf("\n");
    }
    
    int main() {
        int numbers[] = {64, 25, 12, 22, 11};
        int size = sizeof(numbers) / sizeof(numbers[0]);
    
        printf("Unsorted array: \n");
        printArray(numbers, size);
    
        selectionSort(numbers, size);  // Sorting the array
    
        printf("Sorted array: \n");
        printArray(numbers, size);
    
        return 0;
    }
    

    Explanation:

    • The selectionSort function selects the smallest element in the unsorted portion of the array and swaps it with the element at the beginning of the unsorted portion.
    • The printArray function prints the array before and after sorting.

    Output:

    Unsorted array: 
    64 25 12 22 11 
    Sorted array: 
    11 12 22 25 64 
    

    3. Searching Arrays in C

    Searching an array involves finding a specific element in the array. There are different searching algorithms, with Linear Search and Binary Search being the most common.

    Linear Search Algorithm:

    Linear Search is the simplest search algorithm. It checks each element in the array, one by one, to see if it matches the target value. It is a sequential search method.

    Example: Linear Search

    #include <stdio.h>
    
    int linearSearch(int arr[], int size, int target) {
        for (int i = 0; i < size; i++) {
            if (arr[i] == target) {
                return i;  // Return the index if the element is found
            }
        }
        return -1;  // Return -1 if the element is not found
    }
    
    int main() {
        int numbers[] = {5, 10, 15, 20, 25};
        int size = sizeof(numbers) / sizeof(numbers[0]);
        int target = 20;
    
        int result = linearSearch(numbers, size, target);
    
        if (result != -1) {
            printf("Element %d found at index %d.\n", target, result);
        } else {
            printf("Element %d not found in the array.\n", target);
        }
    
        return 0;
    }
    

    Explanation:

    • The function linearSearch searches through the array by comparing each element with the target value.
    • If the target value is found, the index of the element is returned; otherwise, -1 is returned.

    Output:

    Element 20 found at index 3.
    

    Binary Search Algorithm:

    Binary Search works only on sorted arrays. It repeatedly divides the search interval in half. If the target value is less than the middle element, the search continues in the left half; otherwise, it continues in the right half. Binary Search has a time complexity of O(log n), which is faster than Linear Search's O(n).

    Example: Binary Search

    #include <stdio.h>
    
    int binarySearch(int arr[], int size, int target) {
        int left = 0, right = size - 1;
    
        while (left <= right) {
            int mid = left + (right - left) / 2;
    
            // Check if the target is at the middle
            if (arr[mid] == target) {
                return mid;
            }
    
            // If target is greater, ignore the left half
            if (arr[mid] < target) {
                left = mid + 1;
            }
            // If target is smaller, ignore the right half
            else {
                right = mid - 1;
            }
        }
    
        return -1;  // Return -1 if the element is not found
    }
    
    int main() {
        int numbers[] = {5, 10, 15, 20, 25};
        int size = sizeof(numbers) / sizeof(numbers[0]);
        int target = 15;
    
        int result = binarySearch(numbers, size, target);
    
        if (result != -1) {
            printf("Element %d found at index %d.\n", target, result);
        } else {
            printf("Element %d not found in the array.\n", target);
        }
    
        return 0;
    }
    

    Explanation:

    • The function binarySearch works on sorted arrays and efficiently searches for the target using the divide-and-conquer method.
    • The function returns the index of the target if found, or -1 if not.

    Output:

    Element 15 found at index 2.
    

    Summary of Key Concepts

    1. Passing Arrays to Functions:

      • Arrays are passed to functions by reference (through pointers).
      • Modifications inside the function will affect the original array.
    2. Sorting Arrays:

      • Bubble Sort and Selection Sort are two common algorithms to sort arrays.
      • Bubble Sort compares adjacent elements and swaps them if needed.
      • Selection Sort selects the minimum element and swaps it into the correct position.
    3. Searching Arrays:

      • Linear Search checks each element sequentially and is simple but inefficient for large arrays.
      • Binary Search is much faster (O(log n)) but requires the array to be sorted.

    These concepts are foundational for working with arrays in C and allow you to manipulate and search data efficiently.

    ← Previous topic 18
    Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays
    Next topic 20 →
    Multidimensional and Variable Length Arrays

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    9mremaining
    1.5kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals