0% found this document useful (0 votes)
27 views

Function v1

Uploaded by

Ruchita Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Function v1

Uploaded by

Ruchita Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 64

Functions

1
Function
 A program segment that carries out some
specific, well-defined task
 Example
A function to add two numbers
 A function to find the largest of n numbers
 A function will carry out its intended task
whenever it is called or invoked
 Can be called multiple times

2
Why Functions?
 Allows one to develop a program in a
modular fashion
 Divide-and-conquer approach
 Construct
a program from small pieces or
components
 Use existing functions as building blocks for
new programs
 Abstraction: hide internal details (library
functions)

3
 Every C program consists of one or more
functions
 One of these functions must be called main
 Execution of the program always begins by
carrying out the instructions in main
 Functions call other functions as instructions

4
Function Control Flow
void print_banner () int main ()
{ {
print_banner {
printf(“************\n”);
} print_banner (); }

print_banner {
int main () print_banner ();
{ }
...
print_banner (); }
...
print_banner ();

} 5
 Calling function (caller) may pass
information to the called function (callee)
as parameters/arguments
 For example, the numbers to add
 The callee may return a single value to
the caller
 Some functions may not return anything

6
Calling function (Caller)
Called function (Callee) parameter

void main() float cent2fahr(float data)


{ float cent, fahr; {
scanf(“%f”,&cent); float result;
fahr = cent2fahr(cent); result = data*9/5 + 32;
printf(“%fC = %fF\n”, return result;
cent, fahr); }
}

Parameter passed
Returning value
Calling/Invoking the cent2fahr function
7
Defining a Function
 A function definition has two parts:
 The first line, called header
 The body of the function

return-value-type function-name ( parameter-list )


{
declarations and statements
}

8
 The first line contains the return-value-type,
the function name, and optionally a set of
comma-separated arguments enclosed in
parentheses
 Each argument has an associated type
declaration
 The arguments are called formal
arguments or formal parameters
 The body of the function is actually a block of
statement that defines the action to be taken
by the function
9
Parameter passing
 When the function is executed, the value of
the actual parameter is copied to the formal
parameter
parameter passing
int main ()
{ ... double area (double r)
double circum; {
... return (3.14*r*r);
area1 = area(circum);
}
...
}
10
Example of function definition
Return-value type Formal parameters

int gcd (int A, int B)


{
int temp;
while ((B % A) != 0) {
temp = B % A;
BODY
B = A;
A = temp;
} Value returned

return (A);
} 11
Return value
 A function can return a value
 Using return statement
 Like all values in C, a function return value has a type
 The return value can be assigned to a variable in the
caller

int x, y, z;
scanf(“%d%d”, &x, &y);
z = gcd(x,y);
printf(“GCD of %d and %d is %d\n”, x, y, z);
12
Function Not Returning Any Value
 Example: A function which prints if a number is
divisible by 7 or not
void div7 (int n)
{
Return type is void
if ((n % 7) == 0)
printf (“%d is divisible by 7”, n);
else
printf (“%d is not divisible by 7”, n);
return;
} Optional

13
return statement
 In a value-returning function (return type is not void), return
does two distinct things
 specify the value returned by the execution of the function
 terminate that execution of the callee and transfer control
back to the caller
 A function can only return one value
 The value can be any expression matching the return type
 but it might contain more than one return statement.
 In a void function
 return is optional at the end of the function body.
 return may also be used to terminate execution of the
function explicitly.
 No return value should appear following return.

14
void compute_and_print_itax ()
{
float income;
scanf (“%f”, &income); Terminate function
if (income < 50000) { execution before
printf (“Income tax = Nil\n”); reaching the end
return;
}
if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000));
return;
}
if (income < 150000) {
printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);
return ;
}
printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);
}
15
Calling function (Caller)
Called function (Callee) parameter

void main() float cent2fahr(float data)


{ float cent, fahr; {
scanf(“%f”,&cent); float result;
fahr = cent2fahr(cent); result = data*9/5 + 32;
printf(“%fC = %fF\n”, return result;
cent, fahr); }
}

Parameter passed
Returning value
Calling/Invoking the cent2fahr function
16
How it runs
Output
float cent2fahr(float data)
{ $ ./a.out
float result; 32
printf(“data = %f\n”, data); Input is 32.000000
result = data*9/5 + 32;
data = 32.000000
return result;
printf(“result = %f\n”, result); 32.000000C = 89.599998F
}
void main() $./a.out
{ float cent, fahr;
scanf(“%f”,&cent);
-45.6
printf(“Input is %f\n”, cent); Input is -45.599998
fahr = cent2fahr(cent); data = -45.599998
printf(“%fC = %fF\n”, cent, fahr);
-45.599998C = -50.079998F
}
$

17
Function Prototypes
 Function prototypes are usually written at the beginning
of a program, ahead of any functions (including main())
 Prototypes can specify parameter names or just types
(more common)
 Examples:
int gcd (int , int );
void div7 (int number);
 Note the semicolon at the end of the line.

 The parameter name, if specifed, can be anything; but

it is a good practice to use the same names as in the


function definition

18
Function declaration
(prototype)
int factorial (int m);
Another Example int main()
{
int n;
int factorial (int m)
for (n=1; n<=10; n++)
{
printf (“%d! = %d \n”,
int i, temp=1; n, factorial (n) );
for (i=1; i<=m; i++) }
temp = temp
* i; Function call
return (temp); Output
} 1! = 1
2! = 2
Function definition 3! = 6 …….. upto 10!
19
Calling a function
 Called by specifying the function name and parameters
in an instruction in the calling function
 When a function is called from some other function, the
corresponding arguments in the function call are called
actual arguments or actual parameters
 The function call must include a matching actual
parameter for each formal parameter
 Position of an actual parameters in the parameter list
in the call must match the position of the
corresponding formal parameter in the function
definition
 The formal and actual arguments must match in their
data types
20
Example
Formal parameters

double operate (double x, double y, char op)


{
void main () switch (op) {
{ case ‘+’ : return x+y+0.5 ;
double x, y, z; case ‘~’ : if (x>y)
char op; return x-y + 0.5;
... return y-x+0.5;
z = operate (x, y, op); case ‘x’ : return x*y + 0.5;
... default : return –1;
} }
}
Actual parameters 21
22
CALL BY VALUE
 The called function creates new variables to store the value of the
arguments passed to it. Therefore, the called function uses a copy of
the actual arguments to perform its intended task.
 If the called function is supposed to modify the value of the
parameters passed to it, then the change will be reflected only in
the called function. In the calling function, no change will be made
to the value of the variables. This is because all the changes are
made to the copy of the variables and not to the actual variables

23
Example for Call by value
#include <stdio.h>
void add(int n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2

24
Points to remember:
 When arguments are passed by value, the called function
creates new variables of the same data type as the
arguments passed to it.
 The values of the arguments passed by the calling function
are copied into the newly created variables.
 Values of the variables in the calling functions remain
unaffected when the arguments are passed using the call-
by-value technique.

25
Pros & Cons of using Call by value

 Advantage:
 Arguments can be passed as variables, literals, or
expressions
 Disadvantage
 Copying data consumes additional storage space.
 It take a lot of time to copy, thereby resulting in
performance penalty, especially if the function is called
many times.

26
Call by reference
 When the calling function passes arguments to the called function using the call-by-value
method, the only way to return the modified value of the argument to the caller is explicitly
using the return statement.
 A better option is to pass arguments using the call-by-reference technique.
 In this method, we declare the function parameters as references rather than normal
variables.
 When this is done, any changes made by the function to the arguments it received are also
visible in the calling function.
 To indicate that an argument is passed using call by reference, an asterisk (*) is placed after
the type in the parameter list.
 Hence, in the call-by-reference method, a function receives an implicit reference to the
argument, rather than a copy of its value. Therefore, the function can modify the value of
the variable and that change will be reflected in the calling function as well

27
Example of call by reference
#include <stdio.h>
void add(int *);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
Void add(int *n)
{
*n = *n + 10;
printf("\n The value of num in the called function = %d", *n);
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12 add(int *n)

28
Pros and cons of call by reference
 Advantages
 Since arguments are not copied into the new variables, it provides greater time and
space efficiency.
 The function can change the value of the argument and the change is reflected in the
calling function.
 A function can return only one value. In case we need to return multiple values, we
can pass those arguments by reference, so that the modified values are visible in the
calling function.
 Disadvantages
 If inadvertent changes are caused to variables in called function then these changes
would be reflected in calling function as original values would have been overwritten.

29
Example:This function swaps the value of two variables
#include <stdio.h>
void swap_call_val(int, int);
void swap_call_ref(int *, int *);
int main()
{
int a=1, b=2, c=3, d=4;
printf("\n In main(), a = %d and b = %d", a, b);
swap_call_val(a, b);
printf("\n In main(), a = %d and b = %d", a, b);
printf("\n\n In main(), c = %d and d = %d", c, d);
swap_call_ref(&c, &d);
printf("\n In main(), c = %d and d = %d", c, d);
return 0;
}
void swap_call_val(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("\n In function (Call By Value Method) – a = %d and b = %d", a, b);
}
void swap_call_ref(int *c, int *d)
{
int temp;
temp = *c;
*c = *d;
*d = temp;
printf("\n In function (Call By Reference Method) – c = %d and d = %d", *c, *d);
30
}
Output
In main(), a = 1 and b = 2
In function (Call By Value Method) – a = 2 and b = 1
In main(), a = 1 and b = 2
In main(), c = 3 and d = 4
In function (Call By Reference Method) – c = 4 and d = 3
In main(), c = 4 and d = 3

31
Scope of a variable
 Part of the program from which the value of the variable
can be used (seen)
 Scope of a variable - Within the block in which the variable
is defined
 Block = group of statements enclosed within { }
 Local variable – scope is usually the function in which it is
defined
 So two local variables of two functions can have the
same name, but they are different variables
 Global variables – declared outside all functions (even
main)
 scope is entire program by default, but can be hidden in
a block if local variable of same name defined
32
#include <stdio.h>
int A = 1; Variable
void main()Global variable
Scope
{
myProc();
printf ( "A = %d\n", A);
} Hides the global A

void myProc() Output:


{ int A = 2;
if ( A==2 ) A=3
{
A = 3;
printf ( "A = %d\n", A); A=1
}
}

33
Local variables
 A function can define its own local variables
 The locals have meaning only within the function
 Each execution of the function uses a new set of
locals
 Local variables cease to exist when the function
returns
 Parameters are also local

34
Local variables

/* Find the area of a circle with diameter d */


double circle_area (double d)
{ parameter
double radius, area; local
radius = d/2.0; variables
area = 3.14*radius*radius;
return (area);
}

35
Points to note
 The identifiers used as formal parameters are “local”.
 Notrecognized outside the function
 Names of formal and actual arguments may differ

 A value-returning function is called by including it in an


expression
function with return type T (≠ void) can be used anywhere
an expression of type T

36
 Returning control back to the caller
 If nothing returned
 return;

 or,
until reaches the last right brace ending the
function body
 If something returned
 return expression;

37
Some more points
 A function cannot be defined within another
function
 All function definitions must be disjoint
 Nested function calls are allowed
 A calls B, B calls C, C calls D, etc.
 The function called last will be the first to
return
 A function can also call itself, either directly or
in a cycle
 A calls B, B calls C, C calls back A.
 Called recursive call or recursion
38
Example: main calls ncr, ncr calls fact
int ncr (int n, int r)
{
int ncr (int n, int r);
return (fact(n) / fact(r) /
int fact (int n); fact(n-r));
}
void main()
{ int fact (int n)
int i, m, n, sum=0; {
scanf (“%d %d”, &m, &n); int i, temp=1;
for (i=1; i<=m; i+=2) for (i=1; i<=n; i++)
sum = sum + ncr (n, i); temp *= i;
printf (“Result: %d \n”, return (temp);
sum);
}
}
39
Recursive functions
 A function that calls itself is called recursion

40
Recursive functions
 The recursion continues until some condition is
met to prevent it.
 To prevent infinite recursion, if...else statement
 (or similar approach) can be used where one
branch makes the recursive call, and other
doesn't.

41
Example of recursive functions: Sum of Natural Numbers Using Recursion

Output

42
 Initially, the sum() is called from the main() function
with number passed as an argument.
 Suppose, the value of n inside sum() is 3 initially. During the
next function call, 2 is passed to the sum() function. This
process continues until n is equal to 0.
 When n is equal to 0, the if condition fails and the else part
is executed returning the sum of integers ultimately to
the main() function.

43
44
Advantages and Disadvantages of Recursion

 Recursion makes program elegant. However, if


performance is vital, use loops instead as recursion is
usually much slower.
 But recursion is an important concept. It is frequently used
in data structure and algorithms. For example, it is
common to use recursion in problems such as tree
traversal.

45
Storage Classes in C
 Every variable in C programming has two properties: type
and storage class.
 Type refers to the data type of a variable. And, storage
class determines the scope, visibility and lifetime of a
variable.
 There are 4 types of storage class:
1. automatic
2. external
3. static
4. register

46
Local Variable
 The variables declared inside a block are automatic or
local variables. The local variables exist only inside the
block in which it is declared.

Error:
Undeclared identifier i

47
• n1 is local to main() and n2 is local to func()
• You cannot access n1 variable inside func() as it only exists inside the main().
Similarly, you cannot access n2 in main() as it only exists inside the func()

48
Global variables
 Variables that are declared outside of all functions are known as
external or global variables. They are accessible from any function
inside the program.

OUTPUT:
n=7

49
 Suppose, if a global variable is declared in file 1. If you try
to use that variable in file 2, the compiler will complain.
 To solve this problem keyword extern is used in file 2 to
indicate that the external variable is declared in another
file.

50
Register Variable

 The register keyword is used to declare register variables.


Register variables were supposed to be faster than local
variables.
 However, modern compilers are very good at code optimization,
and there is a rare chance that using register variables will make
your program faster. Unless you are working on embedded
systems where you know how to optimize code for the given
application, there is no use of register variables.

51
Static Variable
 Static variables have the property of preserving their value
even after they are out of their scope! Hence, a static
variable preserves its previous value in its previous scope
and is not initialized again in the new scope. 
 Static variable is declared by using the static keyword
 The value of the static variable persists until the end of the
program

52
Static Variable
OUTPUT:

6 11

• During the first function call, the value of c is


initialized to 1. Its value is increased by 5.
Now, the value of c is 6, which is printed on
the screen.
• During the second function call, c is not
initialized to 1 again. It's because c is a static
variable. The value c is increased by 5. Now,
its value will be 11, which is printed on the
screen.

53
Storage Classes in C
 Used to describe the features of a variable/function
 These features basically include the scope, visibility, and
lifetime which help us to trace the existence of a particular
variable during the runtime of a program

54
auto
 Default storage class for all the variables declared inside a
function or a block.
 Hence, the keyword auto is rarely used while writing programs
in C language.
 Auto variables can be only accessed within the block/function
they have been declared and not outside them (which defines
their scope). Of course, these can be accessed within nested
blocks within the parent block/function in which the auto
variable was declared.
 However, they can be accessed outside their scope as well
using the concept of pointers given here by pointing to the
very exact memory location where the variables reside. They
are assigned a garbage value by default whenever they are
declared.  
55
extern
 Extern storage class simply tells us that the variable is defined
elsewhere and not within the same block where it is used.
Basically, the value is assigned to it in a different block and
this can be overwritten/changed in a different block as well. So
an extern variable is nothing but a global variable initialized
with a legal value where it is declared in order to be used
elsewhere. It can be accessed within any function/block.
 Also, a normal global variable can be made extern as well by
placing the ‘extern’ keyword before its declaration/definition in
any function/block. This basically signifies that we are not
initializing a new variable but instead, we are using/accessing
the global variable only. The main purpose of using extern
variables is that they can be accessed between two different
files which are part of a large program.

56
static
 This storage class is used to declare static variables which are
popularly used while writing programs in C language. Static
variables have the property of preserving their value even after
they are out of their scope! Hence, static variables preserve
the value of their last use in their scope. So we can say that
they are initialized only once and exist till the termination of the
program. Thus, no new memory is allocated because they are
not re-declared.
 Their scope is local to the function to which they were defined.
Global static variables can be accessed anywhere in the
program. By default, they are assigned the value 0 by the
compiler. 

57
register
 This storage class declares register variables that have the
same functionality as that of the auto variables. The only
difference is that the compiler tries to store these variables in
the register of the microprocessor if a free register is available.
This makes the use of register variables to be much faster than
that of the variables stored in the memory during the runtime of
the program.
 If a free registration is not available, these are then stored in
the memory only. Usually, a few variables which are to be
accessed very frequently in a program are declared with the
register keyword which improves the running time of the
program. An important and interesting point to be noted here is
that we cannot obtain the address of a register variable using
pointers. 

58
Syntax

storage_class var_data_type var_name;

59
// A C program to demonstrate different storage
// classes
#include <stdio.h>
  
// declaring the variable which is to be made extern
// an initial value can also be initialized to x
int x;
  
void autoStorageClass()
{
  
    printf("\nDemonstrating auto class\n\n");
  
    // declaring an auto variable (simply
    // writing "int a=32;" works as well)
    auto int a = 32;
  
    // printing the auto variable 'a'
    printf("Value of the variable 'a'"
           " declared as auto: %d\n",
           a);
  
    printf("--------------------------------");
}
60
void registerStorageClass()
{
  
    printf("\nDemonstrating register class\n\n");
  
    // declaring a register variable
    register char b = 'G';
  
    // printing the register variable 'b'
    printf("Value of the variable 'b'"
           " declared as register: %d\n",
           b);
  
    printf("--------------------------------");
}

61
void externStorageClass()
{
  
    printf("\nDemonstrating extern class\n\n");
  
    // telling the compiler that the variable
    // x is an extern variable and has been
    // defined elsewhere (above the main
    // function)
    extern int x;
  
    // printing the extern variables 'x'
    printf("Value of the variable 'x'"
           " declared as extern: %d\n",
           x);
  
    // value of extern variable x modified
    x = 2;
  
    // printing the modified values of
    // extern variables 'x'
    printf("Modified value of the variable 'x'"
           " declared as extern: %d\n",
           x);
  
    printf("--------------------------------");
}

62
void staticStorageClass()
{
    int i = 0;
      printf("\nDemonstrating static class\n\n");
  
    // using a static variable 'y'
    printf("Declaring 'y' as static inside the loop.\n"
           "But this declaration will occur only"
           " once as 'y' is static.\n"
           "If not, then every time the value of 'y' "
           "will be the declared value 5"
           " as in the case of variable 'p'\n");
  
    printf("\nLoop started:\n");
  
    for (i = 1; i < 5; i++) {
  
        // Declaring the static variable 'y'
        static int y = 5;
  
        // Declare a non-static variable 'p'
        int p = 10;
  
        // Incrementing the value of y and p by 1
        y++;
        p++;
  
        // printing value of y at each iteration
        printf("\nThe value of 'y', "
               "declared as static, in %d "
               "iteration is %d\n",
               i, y);
  
        // printing value of p at each iteration
        printf("The value of non-static variable 'p', "
               "in %d iteration is %d\n",
               i, p);
    }
      printf("\nLoop ended:\n");
      printf("--------------------------------");
} 63
int main()
{
  
    printf("A program to demonstrate"
           " Storage Classes in C\n\n");
  
    // To demonstrate auto Storage Class
    autoStorageClass();
  
    // To demonstrate register Storage Class
    registerStorageClass();
  
    // To demonstrate extern Storage Class
    externStorageClass();
  
    // To demonstrate static Storage Class
    staticStorageClass();
  
    // exiting
    printf("\n\nStorage Classes demonstrated");
  
    return 0;
}
64

You might also like