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
    CSI-311
    Progress0 / 17 topics
    Topics
    1. Overview of Computers and Programming2. Overview of Languages (e.g., C Language)3. Basics of Structured and Modular Programming4. Basic Algorithms and Problem Solving5. Development of Basic Algorithms6. Analyzing Problems7. Designing Solutions8. Testing Designed Solutions9. Fundamental Programming Constructs10. Translation of Algorithms to Programs11. Data Types12. Control Structures13. Functions14. Arrays15. Records16. Files17. Testing Programs
    CSI-311›Functions
    Programming FundamentalsTopic 13 of 17

    Functions

    7 minread
    1,229words
    Intermediatelevel

    Functions in C Language

    Functions in C are blocks of code that are designed to perform a specific task. A function allows you to write a piece of code once and use it multiple times throughout your program. This helps in organizing code, making it modular, reusable, and easier to debug.

    In C, functions are the building blocks of a program, and they help in reducing the complexity of the program by dividing it into smaller, manageable chunks.


    1. Structure of a Function in C

    A function in C consists of the following parts:

    1. Function Declaration (also known as the function prototype)
    2. Function Definition
    3. Function Call

    a) Function Declaration (Prototype)

    A function declaration provides the compiler with information about the function's name, return type, and parameters (if any). It is usually placed at the beginning of the program or before the function is called.

    • Syntax:

      return_type function_name(parameter_list);
      
    • Example:

      int add(int, int);  // Declaration of a function 'add' that takes two integer arguments and returns an integer
      

    b) Function Definition

    The function definition provides the actual implementation of the function. It contains the code that performs the task specified by the function.

    • Syntax:

      return_type function_name(parameter_list) {
          // body of the function
          // code that performs the task
      }
      
    • Example:

      int add(int a, int b) {
          return a + b;  // Function body that adds two integers and returns the result
      }
      

    c) Function Call

    To use a function, you need to call it in your program. A function call is made by using the function's name followed by the arguments (if any) in parentheses.

    • Syntax:

      function_name(arguments);
      
    • Example:

      int result = add(3, 5);  // Calling the 'add' function with arguments 3 and 5
      printf("The result is: %d", result);  // Printing the result
      

    2. Types of Functions in C

    Functions in C can be categorized based on whether they return a value and whether they take parameters.

    a) Functions Without Return Value (Void Functions)

    If a function does not return any value, the return type is void. These functions are typically used when you need to perform an action but do not need to return any result to the caller.

    • Example:
      void print_message() {
          printf("Hello, world!\n");
      }
      
      // Calling the function
      print_message();
      

    b) Functions With Return Value

    A function that returns a value must have a specified return type (e.g., int, float, char). The return value can be any data type based on the function's return type.

    • Example:
      int multiply(int a, int b) {
          return a * b;
      }
      
      // Calling the function
      int result = multiply(4, 5);
      printf("The result is: %d", result);
      

    c) Functions With Parameters

    A function can take parameters (also called arguments) to work with data passed from the caller. Parameters allow the function to operate on dynamic data.

    • Example:
      int subtract(int x, int y) {
          return x - y;
      }
      
      // Calling the function with arguments
      int result = subtract(10, 3);
      printf("The result is: %d", result);
      

    d) Functions Without Parameters

    A function can also be defined without any parameters if it does not need any data from the caller to perform its task.

    • Example:
      void greet() {
          printf("Hello, User!\n");
      }
      
      // Calling the function without arguments
      greet();
      

    3. Function Return Types in C

    The return type of a function specifies what type of data (if any) the function will return. It can be any valid C data type or void if no value is returned.

    a) Returning a Value

    • Example (Returning an integer):

      int getSquare(int num) {
          return num * num;
      }
      
    • Example (Returning a float):

      float divide(float x, float y) {
          return x / y;
      }
      

    b) Returning void

    If a function does not need to return any value, the return type is void.

    • Example:
      void displayMessage() {
          printf("This is a message.\n");
      }
      

    4. Function Arguments and Parameters

    a) Passing Arguments by Value

    In pass-by-value, the function receives a copy of the argument, meaning that changes to the parameter inside the function do not affect the original argument.

    • Example:
      void increment(int a) {
          a = a + 1;  // This modification only affects the local copy of 'a'
      }
      
      int main() {
          int x = 5;
          increment(x);  // 'x' remains 5 after the function call
          printf("%d", x);  // Output: 5
          return 0;
      }
      

    b) Passing Arguments by Reference (Using Pointers)

    In pass-by-reference, the function receives a reference (or memory address) to the argument, meaning that changes to the parameter inside the function will affect the original argument.

    • Example:
      void increment(int *a) {
          *a = *a + 1;  // This modifies the original value of 'a'
      }
      
      int main() {
          int x = 5;
          increment(&x);  // 'x' is passed by reference, so it changes to 6
          printf("%d", x);  // Output: 6
          return 0;
      }
      

    5. Recursion in C

    A recursive function is a function that calls itself to solve smaller instances of the same problem. Recursion is often used in problems that can be broken down into similar sub-problems, such as calculating factorials, Fibonacci sequences, or traversing trees.

    Example of a Recursive Function (Factorial):

    The factorial of a number n is the product of all positive integers less than or equal to n. Mathematically, it's represented as:

    n! = n * (n - 1) * ... * 1
    

    The factorial of n can be computed using recursion:

    • Example:
      int factorial(int n) {
          if (n == 0 || n == 1) {
              return 1;  // Base case
          }
          return n * factorial(n - 1);  // Recursive case
      }
      
      int main() {
          int result = factorial(5);
          printf("Factorial of 5 is %d", result);  // Output: Factorial of 5 is 120
          return 0;
      }
      

    6. Standard Library Functions

    C provides a rich set of standard library functions that can be used in your programs. These functions are predefined in header files and can be used to perform common tasks, such as input/output, string manipulation, memory management, and mathematical operations.

    Some commonly used standard library headers and their functions:

    • stdio.h: Functions for input/output (e.g., printf, scanf)
    • math.h: Functions for mathematical operations (e.g., sqrt, pow, sin, cos)
    • string.h: Functions for string manipulation (e.g., strlen, strcpy, strcat)
    • stdlib.h: Functions for memory allocation and general utilities (e.g., malloc, free, exit)

    Summary of Functions in C

    1. Function Structure:

      • Declaration (prototype), definition, and call.
    2. Types of Functions:

      • With or without return value
      • With or without parameters
    3. Function Arguments:

      • Pass by value (local copy)
      • Pass by reference (modifies the original variable using pointers)
    4. Recursion:

      • A function calling itself for smaller sub-problems.
    5. Standard Library Functions:

      • C provides a variety of useful functions for input/output, mathematical operations, and string handling.

    Functions help make programs modular, organized, and easier to debug by breaking down complex tasks into simpler, manageable pieces.

    Previous topic 12
    Control Structures
    Next topic 14
    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 time7 min
      Word count1,229
      Code examples0
      DifficultyIntermediate