Class 3 Notes
Class 3 Notes
A function is a set of statements that take inputs, do some specific computation and
produces output.
#include <stdio.h>
Output:
m is 20
Why do we need functions?
Pass by Value: In this parameter passing method, values of actual parameters are copied to function’s formal
parameters
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.
#include <stdio.h>
void fun(int x)
{
x = 30;
}
int main(void)
{
int x = 20;
fun(x);
printf("x = %d", x);
return 0;
}
# include <stdio.h>
void fun(int *ptr)
{
*ptr = 30;
}
int main()
{
int x = 20;
fun(&x);
printf("x = %d", x);
return 0;
}
Following are some important points about functions in C.
2) Every function has a return type. If a function doesn’t return any value,
then void is used as return type.
4) Empty parameter list in C mean that the parameter list is not specified
• User-defined functions
There can be 4 different types of user-defined functions,
they are:
1. Function with no arguments and no return value
Void sum();//function declaration
2. Function with no arguments and a return value
int sum();//function declaration
3. Function with arguments and no return value
Void sum(int,int);//function declaration
4. Function with arguments and a return value
int sum(int,int)
Recursion
// Factorial function
int f(int n)
{
// Stop condition
if (n == 0 || n == 1)
return 1;
// Recursive condition
else
return n * f(n - 1);
}
int main()
{
int n = 5;
printf("factorial of %d is: %d",
n, f(n));
return 0;
}