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

Functions

Functions allow programs to be written in a modular fashion. A function is a block of code that performs a specific task and can be called multiple times. Functions take in parameters, process them, and may return a single value. The main function is where program execution begins. Function prototypes declare a function's return type and parameters so functions can call each other even if defined later.

Uploaded by

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

Functions

Functions allow programs to be written in a modular fashion. A function is a block of code that performs a specific task and can be called multiple times. Functions take in parameters, process them, and may return a single value. The main function is where program execution begins. Function prototypes declare a function's return type and parameters so functions can call each other even if defined later.

Uploaded by

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

Introduction

Function
• A program segment that carries out a specific, well-defined task.
• Examples
• A function to find the gcd of two numbers
• A function to find the largest of n numbers

A function will carry out its intended task whenever it is called


• Functions may call other functions (or itself)
• A function may be called multiple times (with different arguments)

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”.
Function Control Flow

Code
Execution
void print_banner ( )
{ int main () print_banner {
{
printf(“********\n”);

} }
print_banner ();

print_banner {
print_banner ();
int main ( )
{ } }
. . .
print_banner ( ) ;
. . .
print_banner ( ) ; If function A calls function B:
} A : calling function / caller function
B : called function

3
Why Functions?
Functions allow one to develop a program in a modular fashion.
• Codes become readable
• Codes become manageable to debug and maintain

Write your own functions to avoid writing the same code segments multiple times
• If you check several integers for primality in various places of your code, just write a single
primality-testing function, and call it on all occasions

Use existing functions as building blocks for new programs


• Use functions without rewriting them yourself every time it is needed
• These functions may be written by you or by others (like sqrt(), printf())

Abstraction: Hide internal details (library functions)

4
Use of functions: Area of a circle
#include <stdio.h>

/* Function to compute the area of a circle */


float myfunc (float r) Function definition
{ float a;
a = 3.14159 * r * r;
return a; /* return result */ Function argument
}

main()
{
float radius, area;

scanf (“%f”, &radius);


area = myfunc (radius); Function call
printf (“\n Area is %f \n”, area);
}
Use of functions: Area of a circle
#include <stdio.h>

/* Function to compute the area of a circle */


float myfunc (float r) Function definition
{ float a;
a = 3.14159 * r * r;
return a; • A called*/
/* return result Function
function processes argument
information that is passed to it from the
} calling function, and the called function may return a single value (result)
to the calling function.
main()
• Information passed to the function via special identifiers called
{
float radius, area; arguments or parameters.

scanf (“%f”, &radius); • The value is returned by the return statement.


area = myfunc (radius);
Function call
printf (“\n Area is %f \n”, area);
}
Defining a Function #include <stdio.h>

A function definition has two parts:


• The first line return value /* Function to compute the area of a
type circle */
• The body of the function
float myfunc (float r)
{
General syntax: float a;
return-value-type function-name ( parameter-list ) a = 3.14159 * r * r;
{ return a;
declarations and statements }

}
main()
{
The first line contains the return-value-type, the function name, and
float radius, area;
optionally a set of comma-separated arguments enclosed in ( ).
• Each argument has an associated type declaration. scanf (“%f”, &radius);
• The arguments are called formal arguments or formal parameters. area = myfunc (radius);
Example: printf (“\n Area is %f \n”, area);
}
float myfunc (float r)
int gcd (int A, int B)
7
Calling a function
#include <stdio.h>
• Called by specifying the function name and parameters in an
instruction in the calling function.
/* Function to compute the area of a
circle */
float myfunc (float r)
• When a function is called from some other function, the {
float a;
corresponding arguments in the function call are called actual a = 3.14159 * r * r;
arguments or actual parameters. return a;
}
• The function call must include a matching actual parameter for
each formal parameter. main()
{
• Position of an actual parameters in the parameter list in the float radius, area;
call must match the position of the corresponding formal
parameter in the function definition. scanf (“%f”, &radius);
area = myfunc (radius);
• The formal and actual arguments would match in their data printf (“\n Area is %f \n”, area);
types. Mismatches are auto-typecasted if possible. }

• The actual parameters can be expressions possibly involving


other function calls (like f(g(x)+y)).

8
Function Prototypes: declaring a function
Usually, a function is defined before it is called.
• main() is usually the last function in the program written.
• Easy for the compiler to identify function definitions in a single scan through the file.

Some prefer to write the functions after main(). There may be functions that call each other.
• Must be some way to tell the compiler what is a function when compilation reaches a function call.
• Function prototypes are used for this purpose
• Only needed if function definition comes after a call to that function.

• Function prototypes are usually written at the beginning of a program, ahead of any functions (including main()).
• Prototypes must specify the types. Parameter names are optional (ignored by the compiler).
• Examples:
int gcd (int , int );
void div7 (int number);
• Note the semicolon at the end of the line.
• The parameter name, if specified, can be anything; but it is a good practice to use the same names as in the
function definition.

9
Example:
Function prototype / declaration
#include <stdio.h>
int sum( int, int );
int main( ) This program needs a function prototype or
{ function declaration since the function call
int x, y; comes before the function definition.
scanf(“%d%d”, &x, &y);
printf(“Sum = %d\n”, sum(x, y));
}
Function call
int sum (int a, int b)
{
return a + b; Function definition
}

10
Return value
• Sometimes a function is not meant for returning anything
• A function can return a single value
• Such functions are of type void
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 calling Example: A function which prints if a number is divisible
function by 7 or not.

void div7 (int n)


int main( )
{
{ if ((n % 7) == 0)
int x, y, s; printf (“%d divisible by 7”, n);
scanf(“%d%d”, &x, &y); else
printf (“%d not divisible by 7”, n);
s = sum(x, y);
return;
} }
int sum (int a, int b)
{ • The return type is void
return a + b; • The return statement for void functions is optional at
} the end

11
The return statement
void compute_and_print_itax ()
In a value-returning function, return does two distinct {
things: float income;
scanf (“%f”, &income);
• Specify the value returned by the execution of the if (income < 50000) {
function. printf (“Income tax = Nil\n”);
• Terminate the execution of the called function and return; /* Terminates function execution */
transfer control back to the caller function. }
if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000));
A function can only return one value. return; /* Terminates function execution */
• The value can be any expression matching the return }
type. if (income < 150000) {
printf (“Income tax = %f\n”,0.2*(income-60000)+1000);
• It might contain more than one return statement.
return ; /* Terminates function execution */
}
In a void function: printf (“Income tax = %f\n”,0.3*(income-150000)+19000);
}
• "return” is optional at the end of the function body.
• "return” may also be used to terminate execution of
the function explicitly before reaching the end.
• No return value should appear following “return”.

12
Another Example: What is happening here?

int main()
int prime (int x)
{
{
int numb, flag, j=3;
int i, test;
scanf(“%d”,&numb);
i=2, test =0;
while (j <= numb) {
while ((i <= sqrt(x)) && (test ==0))
flag = prime(j);
{
if (flag == 0)
if (x%i==0) test = 1;
printf( “%d is prime\n”, j );
i++;
j++;
}
}
return test;
return 0;
}
}

13
Tracking the flow of control
int main() PROGRAM OUTPUT
{ 5
int prime(int x) numb = 5
int numb, flag, j=3;
{
scanf(“%d”,&numb); int i, test; Main, j = 3
printf(“numb = %d \n”,numb); i = 2; test = 0; In function, x = 3
while (j <= numb) Returning, test = 0
{ printf(“In function, x = %d \n”,x); Main, flag = 0
while ((i <= sqrt(x)) && (test == 0)) 3 is prime
printf(“\nMain, j = %d\n”,j);
flag = prime(j); {
Main, j = 4
if (x%i == 0) test = 1; In function, x = 4
printf(“Main, flag = %d\n”,flag);
i++; Returning, test = 1
} Main, flag = 1
if (flag == 0) printf(“%d is prime\n”,j); printf(“Returning, test = %d \n”,test);
j++; Main, j = 5
} return test; In function, x = 5
return 0; } Returning, test = 0
} Main, flag = 0
5 is prime

14
Nested Functions
A function cannot be defined within another function. It can be called 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.

15
Example: main( ) calls ncr( ), ncr( ) calls fact( )

#include <stdio.h> int ncr (int n, int r)


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

16
Local variables
A function can define its own local variables.
The local variables are known (can be accessed) only within the function in which they are
declared.
• Local variables cease to exist when the function returns.
• Each execution of the function uses a new set of local variables.
Parameters are also local.

/* Find the area of a circle with parameter


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

17
Revisiting nCr

int ncr (int n, int r)


{
return (fact(n)/fact(r)/fact(n-r)); The n in ncr( ) and
} the n in fact( ) are
different
int fact (int n)
{
int i, temp=1;
for (i=1; i<=n; i++)
temp *= i;
return (temp);
}

18
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
• You are encouraged to avoid global variables

19
What happens here?
#include <stdio.h>
int A; /* This A is a global variable */
void main( )
{
A = 1;
myProc( );
A=2
printf ( "A = %d\n", A );
}
Scope of
global A void myProc( )
{
A = 2;

/* other statements */
printf ( "A = %d\n", A ); A=2
}

20
Local Scope replaces Global Scope
#include <stdio.h>
int A; /* This A is a global variable */
void main( )
{
A = 1;
myProc( );
printf ( "A = %d\n", A ); A=1
}

Scope of void myProc( )


global A {
int A = 2; /* This A is a local variable */

Scope of /* other statements */


local A /* within this function, A refers to the local A */

printf ( "A = %d\n", A ); A=2


}

21
Parameter Passing

When the function is called, the value of the actual parameter is copied to the formal parameter

parameter passing

int main ()
{ . . . double area (double r)
double radius, {
a; return (3.14*r*r);
. . . }
a =
area(radius);
. . .
}

22
Parameter Passing by Value in C

• Used when invoking functions

Call by value / parameter passing by value


• Called function gets a copy of the value of the actual argument passed to the
function.
• Execution of the function does not change the actual arguments.
• All changes to a parameter done inside the function are done on the copy.
• The copy is removed when the control returns to the caller function.
• The value of the actual parameter in the caller function is not affected.
• The arguments passed may very well be expressions (example: fact(n-r)).

Call by reference
• Passes the address of the original argument to a called function.
• Execution of the function may affect the original argument in the calling function.
• Not directly supported in C, but supported in some other languages like C++.
• In C, you can pass copies of addresses to get the desired effect.

23
Parameter passing and return: 1

int main()
{
int a=10, b;
printf (“Initially a = %d\n”, a);
b = change (a);
printf (“a = %d, b = %d\n”, a, b); Output
return 0;
} Initially a = 10
Before x = 10
int change (int x)
{ After x = 5
printf (“Before x = %d\n”,x); a = 10, b = 5
x = x / 2;
printf (“After x = %d\n”, x);
return (x);
}

24
Parameter passing and return: 2

int main()
{
int x=10, b;
printf (“M: Initially x = %d\n”, x);
b = change (x);
printf (“M: x = %d, b = %d\n”, x, b); Output
return 0;
} M: Initially x = 10
F: Before x = 10
int change (int x)
{ F: After x = 5
printf (“F: Before x = %d\n”,x);
M: x = 10, b = 5
x = x / 2;
printf (“F: After x = %d\n”, x);
return (x);
}

25
Parameter passing and return: 3
int main()
{ Output
int x=10, y=5;
M1: x = 10, y = 5
printf (“M1: x = %d, y = %d\n”, x, y);
interchange (x, y); F1: x = 10, y = 5
printf (“M2: x = %d, y = %d\n”, x, y); F2: x = 5, y = 10
return 0;
M2: x = 10, y = 5
}

void interchange (int x, int y)


{
int temp;
printf (“F1: x = %d, y = %d\n”, x, y); How do we write an interchange function?
temp= x; x = y; y = temp; (will see later)
printf (“F2: x = %d, y = %d\n”, x, y);
}

26
Header Files
Header files:
• Contain function declarations / prototypes for library functions.
• <stdlib.h> , <math.h> , etc.
• Load with: #include <filename>
• Example: #include <math.h>
• The function definitions of library functions are in the actual libraries (e.g., math library).

We can also create custom header files:


• Create file(s) with function prototypes / declarations.
• Save as filename.h (say).
• Load in other files with #include "filename.h"

28
C preprocessor

• Statements starting with # are handled by the C preprocessor


• May be done by the compiler or by a separate program
• Preprocessing is done before the actual compilation process begins

• The C preprocessor is basically a text substitution tool


• For instance, #include command is replaced by the contents of the specified header file
• Such commands are called preprocessor directives

• We will study another preprocessor directive: #define


• There are more such directives – see book

29
#define: Macro definition
Preprocessor directive in the following form:
#define string1 string2

• Replaces string1 by string2 wherever it occurs before compilation. For example,


#define PI 3.1415926

#define PI 3.1415926
main()
main()
{
{
macro pre-processing float r = 4.0, area;
float r = 4.0, area;
area = 3.1415926 * r * r;
area = PI * r * r;
}
}

30
#define with arguments
#define statement may be used with arguments.
• Example: #define sqr(x) x*x
• How will macro substitution be carried out?
r = sqr(a) + sqr(30); � r = a*a + 30*30;
r = sqr(a+b); � r = a+b*a+b;

• The macro should better be written as:


#define sqr(x) (x)*(x)
r = sqr(a+b); �
WRONG?
r = (a+b)*(a+b);

• Is this still correct?


r = c / sqr(a+b); � r = c / (a+b)*(a+b);

Macros are not functions. They are literally substituted without evaluation.

31

You might also like