Functions In C Programming





In C programming language, a function is a self-contained block of code that performs a specific task. Functions allow you to break down your program into smaller, manageable pieces, making your code more organized, easier to understand, and reusable.


Here are some key points about functions in C:

  • Modularity: Functions promote modularity by encapsulating specific tasks. This makes it easier to understand and maintain the codebase.
  • Reuse: Once defined, functions can be called multiple times from different parts of the program, eliminating the need to rewrite the same code.
  • Abstraction: Functions hide the implementation details of a task, allowing the caller to focus on using the function rather than understanding how it works internally.
  • Return Values: Functions can return a value to the caller, which can be used for further computation or decision making.
  • Arguments: Functions can accept parameters (also called arguments) which are values provided by the caller to customize the behavior of the function.


Types of functions in c

In C programming, functions can be categorized into several types based on their characteristics and usage Like Standard Library Functions, User-defined Functions,Recursive Functions,Function Pointers,Inline Functions,Static Functions,Callback Functions,Library Functions.


There are two main types of functions in C programming:

  1. Library Functions (Predefined Functions).
  2. User-Defined Functions.


  1. Library Functions (Predefined Functions)

    These are functions provided by the C standard library, which are commonly used for tasks like input/output operations (printf, scanf), memory management (malloc, free), string manipulation (strcpy, strlen), mathematical calculations (sin, cos), etc.

    You don't need to define these functions yourself, just include the appropriate header file (e.g., for printf and scanf) to use them.



  2. User-Defined Functions:

    These functions are created by the programmer to perform specific tasks within the program. They offer modularity, code reusability, and better organization.

    You define a user-defined function by specifying its:

    • Return type: The data type of the value the function returns (e.g., int, float, void).
    • Function name: A unique identifier for the function.
    • Parameters (optional): Variables that receive data passed to the function when it's called.
    • Function body: The code that defines the function's logic and performs the desired operation.


    User-defined functions can be further categorized based on their arguments and return values:

    1. Functions with arguments and return values: These functions receive data through their arguments and return a value after processing it.
    2. Functions with arguments and no return value: These functions receive data through their arguments but don't return any value explicitly (they usually return void).
    3. Functions with no arguments and return value: These functions don't receive any data but return a value after performing their task.
    4. Functions with no arguments and no return value: These functions simply execute their code block without receiving or returning any data (they usually return void).


Example:1
Program to Simple Function.
#include <stdio.h>
void show(int x)
{
	printf("\n x= %d", x);
}

int main()
{
	int a = 10;
	show(a);
	return 0;
}
Output:
x = 10


Example:2
Program to Eliminate Function Declaration with Function Definition at Top.
#include <stdio.h>
void show(int x); // Function Declaration //Function Prototype
int main()
{
	int a = 10;
	show(a); // Calling a Function
	return 0;
}

void show(int x) // Function defination
{
	printf("\n x = %d", x);
}
Output:
x= 10
Example:3
3. Program to calculate Simple Interest using Function ( No Argument and No return value).

   
    #include
    void Simp_Int(); // Prototype // Declaration
    
    int main()
    {
     Simp_Int();
     return 0;
    
    }
    
    void Simp_Int()
    {
    float p,r,t,si;
    printf("Enter Principal, Rate and Time :\n");
    scanf("%f %f %f",&p,&r,&t);
    si = (p*r*t)/100;
    printf("\n Simple Interest  = %f",si);
    }
           
        
Output:
               Enter Principal, Rate and Time :
                15
                100
                10

                Simple Interest  = 150.000000
                --------------------------------
                Process exited after 10.66 seconds with return value 0
                Press any key to continue . . .
        
Example:4
4. Program to calculate Simple Interest using Funtion (No Argument but Return Value).

   
    #include
    float Simple_Int();
    int main()
    {
    float si;
    si = Simple_Int();
    printf("\nSimple Interest = %f",si);
    return 0;
    }
    
    float Simple_Int()
    {
    float p,r,t,si;
    printf("Enter Principal, Rate and Time :");
    scanf("%f %f %f",&p,&r,&t);
    si = (p*r*t)/100;
    return si;
    }
      
        
Output:
                Enter Principal, Rate and Time :
                    15
                    100
                    10

                    Simple Interest  = 150.000000
                    --------------------------------
                    Process exited after 10.66 seconds with return value 0
                    Press any key to continue . . .
        
Example:5
5. Program to calculate Simple Interest using Function (Argument but No Return Value ).

    
    #include
    void Simple_Int(float,float,float);
    int main()
    {
        float p,r,t;
        printf("Enter Principal, Rate and Time :");
        scanf("%f %f %f",&p,&r,&t);
        Simple_Int(p,r,t);
        return 0;
    }
    
     void Simple_Int(float p, float r,float t)
     {
        float si;
        si = (p*r*t)/100;
        printf("\nSimple Interest = %f",si);
     }
        
       
        
Output:
                Enter Principal, Rate and Time :
                10
                10
                10
                
                Simple Interest = 10.000000
                --------------------------------
                Process exited after 3.797 seconds with return value 0
                Press any key to continue . . .
        
Example:6
6. Program to Calculate Simple Interest using Function (Argument and Return value).

   
    #include
    float Simple_Int(float,float,float);
        int main()
        {
            float p,r,t,si;
            printf("Enter Principal, Rate and Time :");
            scanf("%f %f %f",&p,&r,&t);
            si=Simple_Int(p,r,t);
            printf("\nSimple Interest = %f",si);
            return 0;
        }
    
        float Simple_Int(float p, float r,float t)
         {
            float si;
            si = (p*r*t)/100;
            return si;
         }
        
                
        
Output:
            Enter Principal, Rate and Time :
            100
            100
            10

            Simple Interest = 1000.000000
            --------------------------------
            Process exited after 6.021 seconds with return value 0
            Press any key to continue . . .
            
        
Example:7
Declaration of multiple function and Calling these from one function.

   
    #include

    // Function prototype can acept only type as well as variable declaration with in parameter.
    
    void add(int , int ); // only type
    void sub(int x, int y); // type with variable declaration
    void div(int,int);
    void mul(int, int);
    void mod(int, int);
    int main()
    {
        add(4,5);
        sub(4,5);
        div(8,2);
        mul(4,2);
        mod(5,2);
    }
    
    void add(int x ,int y)
    {
        printf("The sum is : %d\n",x+y);
    }
    
    void sub(int x, int y)
    {
        printf("The subtraction is : %d\n",x-y);
    }
    void div(int x, int y)
    {
        printf("The Division is : %d\n",x/y);
    }
    void mul(int x, int y)
    {
        printf("The multiplication is : %d\n",x*y);
    }
    void mod(int x, int y)
    {
        printf("The Remainder is : %d\n",x%y);
    }
    
     
                
        
Output:
            The sum is : 9
            The subtraction is : -1
            The Division is : 4
            The multiplication is : 8
            The Remainder is : 1

            --------------------------------
            Process exited after 0.06449 seconds with return value 21
            Press any key to continue . . .
        

variable Type

1. global variable
2. Local variable
3. static variable
4. constant variable

==========> Global variable <============

The variable which is declared outside the function is called global variable.

Reason to use Global variable: ==>

1. we can use global variable in n number of function.
2. Global variable gets memory in main memory.
3. Global variable gets Default value.
4. Its memory gets free when Whole program get finished.

=====================> Local variable <============================

-- The variable which is declared inside the function is called local variable.

Reason to use Local variable: ==>

1. if you want to use a variable for a particular scope.// { } - scope we can declare local variable in function, if else, blocks etc but we can not declare in loop because its iterates n number of times.
2. Gets memory in main memory means ram.
3. we have to assign a value to the local variable otherwise it may consider Garbage value to it..

Example:8
Program to concat string using strcat() function.

    #include

        void test();
     int g; // Globle variable
      int main()
      {
         int x;//=8; // Local variable
         printf("%d\n",x);
         printf("%d\n",g);
         test();
      }
 
      void test()
      {
         int x=5;  //local variable
          printf("%d\n",x);
          printf("%d\n",g);
      }
     
        
Output:
            0
            0
            5
            0
            
            --------------------------------
            Process exited after 0.06643 seconds with return value 2
            Press any key to continue . . .            
        

========> Static Variable <=======

-- The variable which is declared as static is known as static variable.

Points about static :

1. static variable gets memory in ram OR Main memory.
2. Static variable can hold old value of a variable for a function for next execution.

Example:9

    #include
        void counter()
        {
            static
		  	int i=1;
        	printf("%d\n",i);
        	i++;
		}


        int main()
        {
        	counter();
        	counter();
        	counter();
		}
     
      
Output:
        1
        2
        3
        
        --------------------------------
        Process exited after 0.04872 seconds with return value 4
        Press any key to continue . . .
                  
      
Example:10
This example returns a pointer to the first occurrence in the array string of either a or b.

        #include 
        #include 
        
        int main(void)
        {
           char *result, *string = "A Blue Danube";
           char *chars = "ab";
        
           result = strpbrk(string, chars);
           printf("The first occurrence of any of the characters \"%s\" in "
                  "\"%s\" is \"%s\"\n", chars, string, result);
        }
     
      
Output:
        The first occurrence of any of the characters "ab" in "A Blue Danube" is "anube"

        --------------------------------
        Process exited after 0.04989 seconds with return value 81
        Press any key to continue . . .