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›Functions: Modularizing Program in C, Math Library Functions
    Programming FundamentalsTopic 14 of 39

    Functions: Modularizing Program in C, Math Library Functions

    7 minread
    1,139words
    Intermediatelevel

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

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