UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
1
Course : INTRODUCTION TO PROGRAMMING
TOPIC: Functions in C Programming
T
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
What is a Function ?
C function is a self-contained block of statements that can be
executed repeatedly whenever we need it
The idea is to put some commonly or repeatedly done task together and make a
function so that instead of writing the same code again and again for different
inputs, we can call the function.
#include <stdio.h>
/* main function that doesn't receive any parameter
and returns integer. */
int max(int x, int y); //function declaration
int main(void)
{
int a = 10, b = 20,m;
// Calling above function to find max of 'a' and 'b'
m = max(a, b); //function call
printf("m is %d", m);
return 0;
}
/* An example function that takes two
parameters 'x' and 'y' as input and
returns max of two input numbers */
int max(int x, int y) // function definition
{
if (x > y)
return x;
else
return y;
}
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Why do we need Functions ? Or Advantages of Modular Programming
 Functions help us in reducing code redundancy. If functionality
is performed at multiple places in software, then rather than
writing the same code, again and again, we create a function
and call it everywhere. This also helps in maintenance as we
have to change at one place if we make future changes to the
functionality.
 Functions make code modular. Consider a big file having many
lines of codes. It becomes really simple to read and use the
code if the code is divided into functions.
 Functions provide abstraction. For example, we can use library
functions without worrying about their internal working.
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Types of Functions ?
 The system provided these functions and stored in the library. Therefore
it is also called Library Functions.
e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.
 To use these functions, you just need to include the appropriate C
header files.
Built-in(Library) Functions
 These functions are defined by the user at the time of writing the
program.
User Defined Functions
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Parts of Functions ?
1.Function Prototype (function declaration)
2.Function Definition
3.Function Call
Function prototype (Function Declaration)
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Importance of Function Prototype/ Declaration
 Function prototype tells compiler about number of parameters function
takes, data-types of parameters and return type of function.
 By using this information, compiler cross checks function parameters and
their data-type with function definition and function call.
 If we ignore function prototype, program may compile with warning, and may
work properly. But some times, it will give strange output and it is very hard to
find such programming mistakes.
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Importance of Function Prototype/ Declaration
What happens when a function is called before its declaration in C?
In C, if a function is called before its declaration, the compiler assumes return
type of the function as int.
For example, the following program (a) fails in compilation and (b) will work
properly.
(a)
#include <stdio.h>
int main(void)
{
// Note that fun() is not declared
printf("%dn", fun());
return 0;
}
char fun()
{
return 'G';
}
(b)
#include <stdio.h>
char fun()
{
return 'G';
}
int main(void)
{
// Note that fun() is not declared
printf("%dn", fun());
return 0;
}
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Importance of Function Prototype/ Declaration
What about parameters? compiler assumes nothing about parameters.
Therefore, the compiler will not be able to perform compile-time checking of
argument types and arity when the function is applied to some arguments. This
can cause problems.
#include <stdio.h>
int main (void)
{
printf("%d", sum(10, 5));
return 0;
}
int sum (int b, int c, int a)
{
return (a+b+c);
}
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Parts of Functions ?
Function prototype (Function Declaration)
// A function that takes two integers as parameters and returns an integer
int max(int, int);
/* A function that takes an int pointer and an int variable as parameters and returns
pointer of type int */
int *swap(int*,int);
// A function that takes a char as parameters and returns a reference variable
char *call(char b);
// A function that takes a char and an int as parameters and returns an integer
int fun(char, int);
a
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Parts of Functions ?
Function Definition
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Parts of Functions ?
Function Call
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Parameters passing to Functions ?
The parameters passed to function are called actual parameters.
For example, in the below statement 10 and 20 are actual
parameters.
b=addition(10, 20);
The parameters received by function are called formal parameters.
For example, in the below program x and y are formal parameters.
Formal parameters behave like other local variables inside the
function and are created upon entry into the function and
destroyed upon exit.
int addition (int x, int y)
{
// Function Definition
}
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Example: Find cube of any number using function
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Menu Driven program to check Prime, Armstrong and Perfect number
#include <stdio.h>
#include<math.h>
int isPrime(int num);
int isArmstrong(int num);
int isPerfect(int num);
int main()
{
float result;
int choice, num;
printf("Press 1 to check prime Numbern");
printf("Press 2 to check Armstrong Numbern");
printf("Press 3 to check Perfact Numbern");
printf("Enter your choice:n");
scanf(“%d”, &choice);
clrscr();
printf("Enter any number: ");
scanf("%d", &num);
switch (choice)
{
case 1:
if(isPrime(num))
{
printf("%d is Prime number.n", num);
}
else {
printf("%d is not Prime number.n", num); }
break;
case 2:
if(isArmstrong(num))
{
printf("%d is Armstrong number.n", num);
}
else
{
printf("%d is not Armstrong number.n", num);
}
break;
case 3:
if(isPerfect(num))
{
printf("%d is Perfect number.n", num);
}
else
{
printf("%d is not Perfect number.n", num);
}
break;
default:
printf("wrong Inputn");
}
return 0;
}
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Example: Find cube of any number using function
int isPrime(int num)
{
int i;
for(i=2; i<=num/2; i++)
{
if(num%i == 0)
{
return 0;
}
}
return 1;
}
int isArmstrong(int num)
{
int lastDigit, sum, originalNum, digits;
sum = 0;
originalNum = num;
digits = (int) log10(num) + 1;
while(num > 0)
{
lastDigit = num % 10;
sum = sum + round(pow(lastDigit,
digits)); num = num / 10;
}
return (originalNum == sum);
}
int isPerfect(int
num)
{
int i, sum=0, n=num;
for(i=1; i<n; i++)
{
if(n%i == 0)
{ sum += i; }
}
return (num == sum);
}
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Ways to pass Parameters in Functions
Pass by Value: In this parameter passing method, values of actual
parameters are copied to function’s formal parameters and the two
types of parameters are stored in different memory locations. So
any changes made inside functions are not reflected in actual
parameters of caller.
Pass by Reference: Both actual and formal parameters refer to
same locations, so any changes made inside the function are
actually reflected in actual parameters of caller.
There are two most popular ways to pass parameters.
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Ways to pass Parameters in Functions
Pass by Value:
By default, C programming uses call by value to pass arguments. In general,
it means the code within a function cannot alter the arguments used to call the
function. Consider the function swap() definition as follows.
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Ways to pass Parameters in Functions
Pass by Reference:
To pass a value by reference, argument pointers are passed to the functions just
like any other value. So accordingly you need to declare the function parameters
as pointer types as in the following function swap(), which exchanges the values
of the two integer variables pointed to, by their arguments.
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Difference b/w Call by Value and Call by Reference
CALL BY VALUE CALL BY REFERENCE
While calling a function, we pass values of
variables to it. Such functions are known as
“Call By Values”.
While calling a function, instead of passing the
values of variables, we pass address of
variables(location of variables) to the function
known as “Call By References.
In this method, the value of each variable in
calling function is copied into corresponding
dummy variables of the called function.
In this method, the address of actual variables
in the calling function are copied into the
dummy variables of the called function.
With this method, the changes made to the
dummy variables in the called function have
no effect on the values of actual variables in
the calling function.
With this method, using addresses we would
have an access to the actual variables and
hence we would be able to manipulate them.
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
What is recursion ?
Recursion can be defined as the technique of replicating or doing again an
activity in a self-similar way calling itself again and again, and the process
continues till specific condition reaches.
 In the world of programming, when your program lets you call that specific
function from inside that function, then this concept of calling the function
from itself can be termed as recursion, and the function in which makes this
possible is called recursive function.
 The C programming language supports recursion, i.e., a function to call itself.
But while using recursion, programmers need to be careful to define an exit
condition from the function, otherwise it will go into an infinite loop.
0!=1. 5! =5*4!
5*4*3!
5*4*3*2*1
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
What is recursion ?
Factorial of a Number
#include<studio.h>
Int factorial(int number)
{
If( number==1||number==0)
{
Return 1;
Else {
Return(number*factorial(number-1));
}}
Int main()
{ int num;
Printf(“enter the you want the factorial of n”);
Scanf(“%d”,&num);
Printf(“the factorial of %d is %d
n”,num,factorial(num));
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
What is recursion ?
To find nth Fibonacci term
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Advantages of recursion ?
 The main benefit of a recursive approach to algorithm design is that it
allows programmers to take advantage of the repetitive structure
present in many problems.
 Complex case analysis and nested loops can be avoided.
 Recursion can lead to more readable and efficient algorithm
descriptions.
 Recursion is also a useful way for defining objects that have a repeated
similar structural form.
Advantages:
 Slowing down execution time and storing on the run-time stack more
things than required in a non recursive approach are major limitations
of recursion.
 If recursion is too deep, then there is a danger of running out of space
on the stack and ultimately program crashes.
 Even if some recursive function repeats the computations for some
parameters, the run time can be prohibitively long even for very simple
cases.
Disadvantages:
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Custom header File
mainfile.c swap.h
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
Exercise
1. WAP to calculate FACTORIAL OF A NUMBER
using recursion.
2. WAP to print the sum of digits using recursion.
3. WAP to generate the FIBONACCI series using
recursive function
UNIT-III Functions W3schools.in, Tutorialspoint.com
Geeksforgeeks.org, codeforwin.org
THANK YOU

9 functions.pptxFunction that are used in

  • 1.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org 1 Course : INTRODUCTION TO PROGRAMMING TOPIC: Functions in C Programming T
  • 2.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org What is a Function ? C function is a self-contained block of statements that can be executed repeatedly whenever we need it The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. #include <stdio.h> /* main function that doesn't receive any parameter and returns integer. */ int max(int x, int y); //function declaration int main(void) { int a = 10, b = 20,m; // Calling above function to find max of 'a' and 'b' m = max(a, b); //function call printf("m is %d", m); return 0; } /* An example function that takes two parameters 'x' and 'y' as input and returns max of two input numbers */ int max(int x, int y) // function definition { if (x > y) return x; else return y; }
  • 3.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Why do we need Functions ? Or Advantages of Modular Programming  Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to change at one place if we make future changes to the functionality.  Functions make code modular. Consider a big file having many lines of codes. It becomes really simple to read and use the code if the code is divided into functions.  Functions provide abstraction. For example, we can use library functions without worrying about their internal working.
  • 4.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Types of Functions ?  The system provided these functions and stored in the library. Therefore it is also called Library Functions. e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.  To use these functions, you just need to include the appropriate C header files. Built-in(Library) Functions  These functions are defined by the user at the time of writing the program. User Defined Functions
  • 5.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Parts of Functions ? 1.Function Prototype (function declaration) 2.Function Definition 3.Function Call Function prototype (Function Declaration)
  • 6.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Importance of Function Prototype/ Declaration  Function prototype tells compiler about number of parameters function takes, data-types of parameters and return type of function.  By using this information, compiler cross checks function parameters and their data-type with function definition and function call.  If we ignore function prototype, program may compile with warning, and may work properly. But some times, it will give strange output and it is very hard to find such programming mistakes.
  • 7.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Importance of Function Prototype/ Declaration What happens when a function is called before its declaration in C? In C, if a function is called before its declaration, the compiler assumes return type of the function as int. For example, the following program (a) fails in compilation and (b) will work properly. (a) #include <stdio.h> int main(void) { // Note that fun() is not declared printf("%dn", fun()); return 0; } char fun() { return 'G'; } (b) #include <stdio.h> char fun() { return 'G'; } int main(void) { // Note that fun() is not declared printf("%dn", fun()); return 0; }
  • 8.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Importance of Function Prototype/ Declaration What about parameters? compiler assumes nothing about parameters. Therefore, the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems. #include <stdio.h> int main (void) { printf("%d", sum(10, 5)); return 0; } int sum (int b, int c, int a) { return (a+b+c); }
  • 9.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Parts of Functions ? Function prototype (Function Declaration) // A function that takes two integers as parameters and returns an integer int max(int, int); /* A function that takes an int pointer and an int variable as parameters and returns pointer of type int */ int *swap(int*,int); // A function that takes a char as parameters and returns a reference variable char *call(char b); // A function that takes a char and an int as parameters and returns an integer int fun(char, int); a
  • 10.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Parts of Functions ? Function Definition
  • 11.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Parts of Functions ? Function Call
  • 12.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Parameters passing to Functions ? The parameters passed to function are called actual parameters. For example, in the below statement 10 and 20 are actual parameters. b=addition(10, 20); The parameters received by function are called formal parameters. For example, in the below program x and y are formal parameters. Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. int addition (int x, int y) { // Function Definition }
  • 13.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Example: Find cube of any number using function
  • 14.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Menu Driven program to check Prime, Armstrong and Perfect number #include <stdio.h> #include<math.h> int isPrime(int num); int isArmstrong(int num); int isPerfect(int num); int main() { float result; int choice, num; printf("Press 1 to check prime Numbern"); printf("Press 2 to check Armstrong Numbern"); printf("Press 3 to check Perfact Numbern"); printf("Enter your choice:n"); scanf(“%d”, &choice); clrscr(); printf("Enter any number: "); scanf("%d", &num); switch (choice) { case 1: if(isPrime(num)) { printf("%d is Prime number.n", num); } else { printf("%d is not Prime number.n", num); } break; case 2: if(isArmstrong(num)) { printf("%d is Armstrong number.n", num); } else { printf("%d is not Armstrong number.n", num); } break; case 3: if(isPerfect(num)) { printf("%d is Perfect number.n", num); } else { printf("%d is not Perfect number.n", num); } break; default: printf("wrong Inputn"); } return 0; }
  • 15.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Example: Find cube of any number using function int isPrime(int num) { int i; for(i=2; i<=num/2; i++) { if(num%i == 0) { return 0; } } return 1; } int isArmstrong(int num) { int lastDigit, sum, originalNum, digits; sum = 0; originalNum = num; digits = (int) log10(num) + 1; while(num > 0) { lastDigit = num % 10; sum = sum + round(pow(lastDigit, digits)); num = num / 10; } return (originalNum == sum); } int isPerfect(int num) { int i, sum=0, n=num; for(i=1; i<n; i++) { if(n%i == 0) { sum += i; } } return (num == sum); }
  • 16.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Ways to pass Parameters in Functions Pass by Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller. Pass by Reference: Both actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller. There are two most popular ways to pass parameters.
  • 17.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Ways to pass Parameters in Functions Pass by Value: By default, C programming uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows.
  • 18.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Ways to pass Parameters in Functions Pass by Reference: To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.
  • 19.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Difference b/w Call by Value and Call by Reference CALL BY VALUE CALL BY REFERENCE While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”. While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References. In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function. In this method, the address of actual variables in the calling function are copied into the dummy variables of the called function. With this method, the changes made to the dummy variables in the called function have no effect on the values of actual variables in the calling function. With this method, using addresses we would have an access to the actual variables and hence we would be able to manipulate them.
  • 20.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org What is recursion ? Recursion can be defined as the technique of replicating or doing again an activity in a self-similar way calling itself again and again, and the process continues till specific condition reaches.  In the world of programming, when your program lets you call that specific function from inside that function, then this concept of calling the function from itself can be termed as recursion, and the function in which makes this possible is called recursive function.  The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop. 0!=1. 5! =5*4! 5*4*3! 5*4*3*2*1
  • 21.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org What is recursion ? Factorial of a Number #include<studio.h> Int factorial(int number) { If( number==1||number==0) { Return 1; Else { Return(number*factorial(number-1)); }} Int main() { int num; Printf(“enter the you want the factorial of n”); Scanf(“%d”,&num); Printf(“the factorial of %d is %d n”,num,factorial(num));
  • 22.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org What is recursion ? To find nth Fibonacci term
  • 23.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Advantages of recursion ?  The main benefit of a recursive approach to algorithm design is that it allows programmers to take advantage of the repetitive structure present in many problems.  Complex case analysis and nested loops can be avoided.  Recursion can lead to more readable and efficient algorithm descriptions.  Recursion is also a useful way for defining objects that have a repeated similar structural form. Advantages:  Slowing down execution time and storing on the run-time stack more things than required in a non recursive approach are major limitations of recursion.  If recursion is too deep, then there is a danger of running out of space on the stack and ultimately program crashes.  Even if some recursive function repeats the computations for some parameters, the run time can be prohibitively long even for very simple cases. Disadvantages:
  • 24.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Custom header File mainfile.c swap.h
  • 25.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org Exercise 1. WAP to calculate FACTORIAL OF A NUMBER using recursion. 2. WAP to print the sum of digits using recursion. 3. WAP to generate the FIBONACCI series using recursive function
  • 26.
    UNIT-III Functions W3schools.in,Tutorialspoint.com Geeksforgeeks.org, codeforwin.org THANK YOU