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
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Passing Arrays to Function, Sorting and Searching Arrays
    Programming FundamentalsTopic 19 of 39

    Passing Arrays to Function, Sorting and Searching Arrays

    9 minread
    1,520words
    Intermediatelevel

    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 load past papers

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