Function

Details of Terms used in function

Terms
Works

Another Example

declaration
definition

Why We Use Functions?

Scope of a variable in Functions

Scope

Calling Convention

Example
Example

Points to note

Advanced Features of Functions

We will see the advanced some features of functions are given below:-

Function Declaration and Prototypes

Some more points

Example:main calls ncr, ncr calls fact

int ncr (int n, int r);
int fact (int n);
void main()
{
	int i, m, n, sum=0;
	scanf ("%d %d", &m, &n);
		for (i=1; i <=m; i+=2)
			sum = sum + ncr (n, i);
printf ("Result: %d \n",sum);
}
//ncr function definition
int ncr (int n, int r)
{
return (fact(n) / fact(r) / fact(n-r));
}
//fact function declaration
int fact (int n)
{
	int i,temp=1;
	for (i=1; i<=n; i++)
		temp *= i;
	return (temp);
}
      

Call by Value and Call by Reference

It is used when invoking functions:

Call by value

Call by reference

library Functions

  • Set of functions already written for you,and bundled in a "library"
    • Example:printf, scanf, getchar etc.
  • C library provides a large number of functions for many things
  • We look at functions for mathematical use.
  • Math library Functions

  • Math library functions
    • perform common mathematical calculations
    • Must include a special header file
      • #include < math.h >
  • Example
    • printf("%f", sqrt(900.0));
    • Calls function sqrt, which returns the square root of its argument
  • Return values of math functions can be float/double/long double
  • Arguments may be constants, variables, or expressions
Function Working of function
double acos(double x) Compute arc cosine of x.
double asin(double x) Compute arc sine of x.
double atan(double x) Compute arc tangent of x.
double atan2(double y, double x) Compute arc tangent of y/x.
double cos(double x) Compute cosine of angle in radians.
double cosh(double x) Compute the hyperbolic cosine of x.
double sin(double x) Compute sine of angle in radians.
double sinh(double x) Compute the hyperbolic sine of x.
double tan(double x) Compute tangent of angle in radians.
double tanh(double x) Compute the hyperbolic tangent of x.
double ceil(double x) Get smallest integral value that exceeds x.
double floor(double x) Get largest integral value less than x.
double exp(double x) Compute exponential of x.
double fabs (double x) Compute absolute value of x.
double log(double x) Compute log to the base e of x.
double log10 (double x) Compute log to the base 10 of x.
double pow (double x, double y) Compute x raised to the power y.
double sqrt(double x) Compute the square root of x.

Introduction to Pointers

Pointer Variable Definitions and Initialization

Pointer Notation

Back to Function Calls

A callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function. In C, a callback function is a function that is called through a function pointer.
Below is a simple example in C to illustrate the above definition to make it more clear:

  // A simple C program to demonstrate callback
#include <stdio.h >
void Ask()
{
	printf("I am function Ask\n");
}
// callback function
void Blow(void (*ptr)())
{
	(*ptr) (); // callback to Ask
}

int main()
{
	void (*ptr)() = &A;
	
	// calling function Blow and passing
	// address of the function Ask as argument
	Blow(ptr);
return 0;
}

Conclusions

(a)If we want that the value of an actual argument should not get changed in the function being called, pass the actual argument by value.
(b)If we want that the value of an actual argument should get changed in the function being called, pass the actual argument by reference.
(c)If a function is to be made to return more than one value at a time then return these values indirectly by using a call by reference.

Recursion

The Recursive function is a function that calls itself to solve the problem.

When should we use recursion?

If any problem can be divided into multiple smaller version of the same problem, we can use Recursive approach to solve that problem.

Calculate the factorial of a given number.
fact(3) = 6 (3 * 2 * 1)
This problem can be divided into three smaller versions.
 Declare fact = 1
 1. fact = fact * 3
 2. fact = fact * 2
 1. fact = fact * 1

Basic Rules of Recursion

1. The recursive function should call itself.

2. The recursive function should have an ending point where it doesn't make further recursive calls. Also called as the base case. Base case will not need any recursive call to solve.

Example Base cases

Factorial of 0 is 1 and 1 is 1.
Fibonacci of 0 is 0 and 1 is 1.
The above cases are straightforward and those cases don't need any recursive call.

3. All the recursive calls should align towards the base case.

Example

When calculating factorial(5). Here, base case is factorial(0) = 1 || factorial(1) = 1.
Recursive functions should go like factorial(5), factorial(4),factorial(3),factorial(2), finally ends with factorial(1) or factorial(0).
If it goes in another way like factorial(6)....factorial(100) etc. The recursion won't end.

Let's solve the factorial problem using recursion

Algorithm

1.Find the base case. factorial(0) = 1 || factorial(1) = 1.
2. Write the factorial function and call itself recursively untill it meets the base case.
3. Calculate and return the answer.

int factorial(int n)
{
    //base case fact(0) = fact(1) = 1 
    if(n <= 1)
        return 1;
    //calculate the factorial
    //recursively the call the above function
    return n * factorial(n - 1);
}

Factorial using Recursion

  #include <stdio.h>
  int fact(int n)
  {
      if(n <= 1)
          return 1;
      return n * fact(n-1);
  }
  int main()
  {
      int n;
      scanf("%d",&n);
      if(n >= 0)
          printf("%d\n",fact(n));
      return 0;
  }

Visualizing the above recursive function

The best way of understanding the recursion is by visualizing it.
Let's understand how factorial(3) works.

Stack Overflow in Recursion

In recursion, the new function call will be created in stack memory section.
If our recursive function doesn't have any base case or the recursive function call doesn't align towards the base case, it will keep on create function calls in the stack memory section.
At some point in time, the recursive function call overflows the stack memory section as it doesn't have any stopping point.
This is also called as the stack overflow in recursion.

Recursive function won't have any base case - Stack Overflow

#include<stdio.h1>
int fact(int n)
{
    return n * fact(n-1);
}
int main()
{
    int n;
    scanf("%d",&n);
    if(n >= 0)
        printf("%d\n",fact(n));
    return 0;
}

The above recursive function doesn't have any base case.
If the given input is 3, the recursive calls will be fact(2), fact(1), fact(0), fact(-1),.... and so on. It will never end.
This will overflows the stack memory section.

Chapter 6 Quiz

1.When function calls itself, it is known as ______.
2.A recursive function without if and else conditions will always lead to?
3.What will be Output of Program?
    #include< stdio.h >
    int fun(int n)
    {
      if (n==4)
        return n;
      else  
        return 2*fun(n+1);
    }
    int main()
    {
      printf("%d",fun(2));
      return 0;
    }
  
4.In the C language
5.Consider the following C function:
    int f(int n)
    {
    static int i = 1;
    if(n>=5) return n;
    n = n+1;
    i++;
    return f(n);
    }
    The value returned by f(1) is
  
Home Page
Top of Page
Go Next