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-112Functions Modular Prog…
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
    7 min read
    Topic 14 of 39
    Topic Study Note Illustration
    14

    Functions: Modularizing Program in C, Math Library Functions

    Functions in C allow us to break down a program into smaller, reusable blocks of code. This is known as modularization . Functions not only improve the...

    Functions in C: Modularizing Program and Math Library Functions

    Functions in C allow us to break down a program into smaller, reusable blocks of code. This is known as modularization. Functions not only improve the structure of the program but also make it easier to maintain and debug. In addition to creating your own functions, C also provides several math library functions to perform common mathematical operations. Let’s explore both concepts in detail.


    1. Modularizing a Program Using Functions in C

    A function in C is a self-contained block of code that performs a specific task. By using functions, you can modularize your program, meaning you break down a large program into smaller, easier-to-manage pieces.

    Why Use Functions?

    • Reusability: Functions allow you to write a piece of code once and use it in multiple places.
    • Readability: Breaking a program into functions makes the code more organized and easier to read.
    • Maintainability: If a change is required, you only need to modify the function code, not the entire program.
    • Debugging: It’s easier to identify problems when the program is divided into smaller, more manageable functions.

    Function Definition:

    The general syntax for defining a function in C is:

    return_type function_name(parameter1, parameter2, ...) {
        // Body of the function
        // Code to perform a task
        return value;  // Optional, depending on the return_type
    }
    
    • return_type: Specifies what type of value the function returns (e.g., int, float, void).
    • function_name: The name you give to the function (e.g., addNumbers, calculateArea).
    • parameters: A list of values (optional) that the function takes as inputs.

    Example: A Simple Function

    Let’s create a simple function to calculate the sum of two numbers.

    #include <stdio.h>
    
    // Function declaration
    int add(int a, int b);
    
    int main() {
        int result = add(5, 3);  // Function call
        printf("The sum is: %d\n", result);
        return 0;
    }
    
    // Function definition
    int add(int a, int b) {
        return a + b;
    }
    

    Explanation:

    • Function Declaration: We declare the function add before the main function. This tells the compiler about the function's name and parameters.
    • Function Call: Inside main(), we call add(5, 3) to get the sum of 5 and 3.
    • Function Definition: The function add takes two integer parameters, a and b, and returns their sum.

    Output:

    The sum is: 8
    

    2. Function with No Return Value: void Functions

    If a function does not need to return any value, we use the void return type. A function that does not return anything is typically used to perform a task, such as printing a message, updating a variable, or modifying global data.

    Example: A void Function

    #include <stdio.h>
    
    // Function declaration
    void greetUser();
    
    int main() {
        greetUser();  // Function call
        return 0;
    }
    
    // Function definition
    void greetUser() {
        printf("Hello, welcome to the C programming tutorial!\n");
    }
    

    Explanation:

    • The function greetUser does not return a value; it simply prints a greeting message.

    Output:

    Hello, welcome to the C programming tutorial!
    

    3. Function with Multiple Return Values

    In C, a function can only return a single value. However, you can return multiple values by using pointers or structs.

    Example: Returning Multiple Values Using Pointers

    #include <stdio.h>
    
    // Function declaration
    void calculateRectangle(int length, int width, int *area, int *perimeter);
    
    int main() {
        int length = 5, width = 3;
        int area, perimeter;
        
        calculateRectangle(length, width, &area, &perimeter);  // Passing addresses
    
        printf("Area: %d\n", area);
        printf("Perimeter: %d\n", perimeter);
        
        return 0;
    }
    
    // Function definition
    void calculateRectangle(int length, int width, int *area, int *perimeter) {
        *area = length * width;  // Dereferencing pointers to set the value
        *perimeter = 2 * (length + width);  // Dereferencing pointers to set the value
    }
    

    Explanation:

    • The function calculateRectangle calculates both the area and perimeter of a rectangle.
    • Instead of returning multiple values, we use pointers (*area, *perimeter) to modify values in the calling function.

    Output:

    Area: 15
    Perimeter: 16
    

    4. Math Library Functions in C

    The math library in C provides a set of functions that perform common mathematical operations, such as calculating square roots, powers, trigonometric functions, logarithms, and more. To use these functions, you must include the math.h header file.

    Common Math Functions in C:

    1. sqrt(x): Calculates the square root of x.
    2. pow(x, y): Calculates x raised to the power of y (i.e., x^y).
    3. abs(x): Calculates the absolute value of x.
    4. sin(x), cos(x), tan(x): Trigonometric functions that calculate the sine, cosine, and tangent of x (in radians).
    5. log(x): Calculates the natural logarithm (base e) of x.
    6. log10(x): Calculates the base-10 logarithm of x.
    7. exp(x): Calculates the exponential function e^x.

    To use the math functions, remember to link the math library during compilation. For example, if you're using GCC, you can compile with -lm to link the math library.

    Example: Using Math Library Functions

    #include <stdio.h>
    #include <math.h>  // Include the math library
    
    int main() {
        double num = 16.0;
        double result;
        
        result = sqrt(num);  // Calculate the square root
        printf("Square root of %.2f is %.2f\n", num, result);
    
        result = pow(2, 3);  // Calculate 2 raised to the power of 3
        printf("2 raised to the power of 3 is %.2f\n", result);
    
        result = log(10);  // Calculate the natural logarithm of 10
        printf("Natural logarithm of 10 is %.2f\n", result);
        
        return 0;
    }
    

    Explanation:

    • The sqrt(num) function calculates the square root of num.
    • The pow(2, 3) function calculates 2^3.
    • The log(10) function calculates the natural logarithm of 10.

    Output:

    Square root of 16.00 is 4.00
    2 raised to the power of 3 is 8.00
    Natural logarithm of 10 is 2.30
    

    5. Summary of Key Concepts

    • Functions in C: Functions allow you to modularize your program into smaller, reusable blocks. This helps in improving code readability, maintainability, and debugging.
    • Function Declaration: Specifies the return type, function name, and parameters before the function is defined.
    • void Functions: Functions that do not return any value.
    • Passing Multiple Values: C allows passing values back to the calling function using pointers.
    • Math Library Functions: C provides a variety of functions for mathematical operations through the math.h library. These functions include sqrt(), pow(), log(), and more.

    By using functions and math library functions in C, you can create well-organized programs that handle mathematical operations and tasks efficiently.

    ← Previous topic 13
    Program Control: for, switch, do...while, break, continue, Logical Operators
    Next topic 15 →
    Function Definitions and Prototypes, Function-Call Stack and Stack Frames

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals