Department of Computer
Engineering
and Information Technology
Chapter 5
Functions
6-2-2020 YTU
Functions
• What is a function?
- A function is a sub-unit of a program which performs a
specific task
- A function can take any number of arguments mixed in
any way
- A function can return at most one argument
Need for Functions?
• Algorithms for solving more complex problems become more
difficult and hence difficult to design
• Even if algorithms are known, its implementation becomes more
difficult because size of the program is longer
• As programs become larger and complex, debugging and testing
becomes more difficult
• As programs become larger and complex, more make the
documentation is required to program
understandable for people who will use and maintain the
program
Why use Functions?
• Avoids rewriting the same code over and over • Easier to write
programs and keep track of what they are doing
Simple
Function(1) Function
Declaration (2) Calling a
Function
(3) The Function Definition
No Return Type
vs Return Type
• We can declare variables within
a function just like we can
within main() - these
variables will be deleted when
we return from the function
No Return Type
#include <stdio.h>
Definitions• Defining a
main() Function
{
printf("Welcome to Programming Class"); } return_type function_name(parameter-
Return Type list) {
#include <stdio.h> body of the function
int main() }
{
printf("Welcome to Programming
Class" ); Return type: A function may return a
return 0;
value.
}
Function
int getsum(int x, int y) { }
return (x +y);
A data type of the result (default int)
void - function returns nothing
Function Name: The actual name of the function
message();//function call
Parameters: Function body: message();
The value is referred to as actual
parameter or argument The function }
void message() //function definition {
body contains a collection of statements printf("\nJewel Thief!");
that define what the function does }
#include <stdio.h>
void message();
//function declaration
main()
{ Program Output
Jewel Thief! - Any function can
Jewel Thief! be called from other
Outline functions
Call function
- A function can be called any number of
times
#include <stdio.h>
main()
{
printf("\nI am in main");
italy();
printf("\nI am finally back in main”);
} Program Output
italy() I am in main
{ I am in italy
printf("\nI am in italy"); I am finally back in main
} #include <stdio.h>
Outline main()
{
printf("\nI am in main");
Call function italy();
printf("\nI am finally back in main”); - Any function can be called from other
} functions
italy()
{
printf("\nI am in italy");
brazil();
printf("\nI am back in italy"); }
brazil()
{
printf("\nI am in brazil”);
argentina();
}
argentina()
{
printf("\nI am in argentina"); } Program Output
Outline I
I
am
am
in main
in italy
I am in brazil
Call function I am in argentina
I am back in italy
I am finally back in main
Invoking a Function
• The user-defined functions are accessed from a function simply by its
name and actual arguments / parameters enclosed with in parentheses. •
These actual arguments are used to pass values of formal arguments
defined in the function.
• When the function call is encountered, the control is transferred to the
called function.
• The formal arguments are copied by actual arguments and the
execution of the function is carried out.
• When the return statement is executed or last statement has finished its
execution, the control is transferred back to the place of function call in
the calling function.
Scope Rule of
Functions Look at the following
program.
void fun(int x);
main( )
{
int a = 30 ; Actual argument
fun ( a ) ; //fun(30);
printf ( "\n The value of variable is %d",
a);}
fun ( int x ) //fun(int x =30)
{ Formal argument
x = 60 ;
printf ( "\nThe value of variable is %d", x ) ; } The value of variable is 60 The value of variable
is 30
Output
Local and Global Variables
• The variables declared inside a function are local to that function.
It can be accessed only with in that function.
• Memories for the local variables are allocated only when the
function is invoked and de-allocated when the control returns to
the calling function.
• Local variables are also known to be automatic variables. • The
variables declared outside of all function are global variables. These
global variables are visible to all functions.
Local and Global
VariablesExample : Usage of Global Variables
#include <stdio.h>
int a=0; float b;
void fun(); printf(“%d”,a);
/* Global variable */
int main()
/* Global variable */
{
int a=5;
float b=1.2;
fun();
}
printf(“%d”,a); void fun()
{
a+=10; /* Local variable*/
} What will be the output?
Local and Global
Variables#include <stdio.h>
int a, b; /*Global variables*/
void fun(int a);
int main()
{ a = 1; b = 2; /*Local variable*/
fun(a);
printf(“%d %d”,a,b);
}
void fun(int a)
{ a = 3; { int b = 4;
/*local variable*/ /*local variable*/
printf(“%d %d”,a,b); }
printf(“%d %d”,a,b); Output
b = 5;
} 34
32
15
Local and Global
Variables#include <stdio.h>
int a, b; /*Global variables*/
void fun(int x);
int main()
{ a = 1; b = 2; /*Local variable*/
fun(a);
printf(“%d %d”,a,b);
}
void fun(int x)
{ x = 3; { int b = 4;
/*local variable*/ /*local variable*/
printf(“%d %d”,x,b); Output
}
printf(“%d %d”,x,b); 34
b = 5; 32
} 15
Function Declaration and
Prototypes Example: Write a program to find out square of a
number using a function.
main( )
{
float square (float x);
float a, b ;
printf ( "\nEnter any number " ) ;
scanf ( "%f", &a ) ;
b = square ( a ) ; // calling a function
printf ( "\nSquare of %f is %f", a, b ) ;
}
float square ( float x )
{ y = x * x ; return ( y ) ; }
float y ; Enter any number 1.5 Square of 1.5 is 2.250000
Enter any number 2.5 Square of 2.5 is 6.250000
Passing Values between FunctionsOutline
// Finding the sum of three integers calsum(int x, int y, int z)
#include <iostream> {
using namespace std; int d;
main() d = x + y + z;
{ return(d);
int a, b, c, sum; }
cout << "\nEnter any three integers:”;
cin >> a >> b >> c;
sum = calsum(a,b,c); // calling Program Output
function cout << “\nSum = “ << sum;
} Enter any three numbers: 10 20 30
// Function definition Sum = 60
Input values Call function Function definition
Passing Values between FunctionsOutline
// Finding the sum of three integers Program Output
#include <stdio.h>
int calsum(int x, int y, int z) Enter any three numbers: 10 20 30
main() Sum = 60
{
int a, b, c, sum; Input values Call function Function
printf("\nEnter any three integers:”);
Scanf(“%d %d %d”,a,b,c);
definition
sum = calsum(a,b,c); // calling // Finding the biggest of two
function printf(“\nSum = %d“, sum); integers
}
// Function definition
#include <iostream>
int calsum(int x, int y, int z) using namespace std;
{
int d;
d = x + y + z;
Outline
return(d); Function
}
declaration (two
int find_big(int,int); int main( ) { int num1, num2, big;
// find_big function parameters) Input values Call function
cout << “Enter two integers:\n” ; }
cin >> num1 >> num2; int find_big(int a, int b)
big=find_big(num1,num2); // find_big { if ( a > b) return a;
function call cout << " The biggest is : " << else return b;
big ; }
system("pause");
Function definition
return 0;
Enter two integers: 22
85 The biggest is: 85
Passing Arguments between
FunctionsThere are two approaches to passing
arguments to a function.
▪ Call by Value
- copies the ‘values’ of an argument calling a function
- changes made to the parameter have no effect on the values of actual
arguments in the calling function
• Call by Reference
- a reference to an argument (not the value of the argument) is passed to
the variable
(addresses of actual arguments is called a reference)
- changes on the values of actual arguments in the calling function
Call by Value
Outline
#include <iostream>
using namespace std; int t;
void swapv(int x, int y); t = x;
main() x = y;
{ y = t;
int a=10, b=20; cout << "x= " << x << " " << "y= " << y << endl; }
swapv(a,b); Values of a and b
cout << "a= " << a << " " << "b= " << b << endl; }
remain
// Function definition
void swapv(int x, int y) unchanged even after exchanging the
{ values of x and y
x = 20 y =
10 a = 10 b
= 20
int t;
Call by Reference t = x;
x = y;
#include <iostream> y = t;
using namespace std; cout << "x= " << x << " " << "y= " << y << endl; }
void swapr(int& x, int& y);
main()
{ Outline
int a=10, b=20;
swapr(a, b); To
cout << "a= " << a << " " << "b= " << b << endl; } exchange
// Function definition the values of a and b using their addresses
void swapr(int & x, int& y) stored in x and y
{
x = 20 y =
10 a = 20 b
= 10
Call by Value
/* Exchange the value of two integers*/
#include <stdio.h>
swapv(int x, int y); /* Function Declaration */ main()
{
int a=10, b =20;
swapv(a,b); /* function calling to get a value */ printf(“\
na=%d b=%d", a, b);
}
swapv(int x, int y) { printf(“\n x=%d y=%d”, x, y); }
int temp;
temp = x; x = 20 y = 10
x = y; a = 10 b = 20
y = temp;
/* Function Definition */
Values of a and b remain unchanged even after exchanging the values of x and y
swapr(int *x, int *y); /* Function Declaration */
Call by Reference main()
{
/* Exchange the value of two integers*/ int a=10, b =20;
[Link] ?v=HEiPxjVR8CU&t=496s
#include <stdio.h>
swapr(&a,&b); *x = *y;
printf(“a=%d b=%d",a,b); } *y = temp;
swapr(int *x, int *y) /* function calling to get a value */ /* Function
{
int temp;
temp = *x; Definition */
printf(“x=%d y=%d \n”, * x, * y); } exchange the values of a and b using their
addresses stored in x and y
x = 20 y = 10
a = 20 b = 10
printf("Area=%f", area);
Call by Reference printf("\nPerimeter= %f", perimeter);
system("pause");
#include <stdlib.h> }
#include <stdio.h>
float areaperi(int r, float *a, float *p);
main()
{
int radius; float areaperi(int r, float *a, float *p)
float area, perimeter; {
*a = 3.14*r*r;
printf("\nEnter radius of a circle"); *p = 2 * 3.14 * r;
scanf("%d", &radius); return(*a, *p);
}
area, perimeter = areaperi(radius, &area,
&perimeter);
Enter radius of a Area = 78.500000
circle 5
Perimeter = 31.000000
Remark
▪ Call by Value
- If we want the value of an actual argument should not get
changed in the function being called, pass the actual argument
by value
• Call by Reference
- If we want the value of an actual argument should get changed
in the function being called, pass the actual argument by
reference.
- Ifa function is to made to return more than one value at a time,
these values indirectly by using a call by reference.
Non-Recursion
Example: Write a program that computes factorial of a number.
Factorial Function : n! = n * (n-1)!
Base Criteria is 0! =1
main( ) f=f*i;
{ return( f ) ;
int a, fact ; }
printf( "\nEnter any number " ) ; scanf( main()
"%d", &a ); {
int a, fact;
fact = factorial(a); printf("Enter any number\n");
printf( "Factorial value = %d", fact ) ; } scanf("%d", &a);
int factorial( int x ) fact = factorial(a);
{ printf("Factoiral value=%d\n", fact); }
int f = 1, i ; int factorial(int x)
for ( i = x ; i >= 1 ; i-- )
{ f = f * i;
int f=1, i; return( f );
for ( i=1; i<=x; i++) }
Recursion
▪ In C, it is possible for the function to call themselves. ▪ A function
is called ‘recursive’ if a statement within the body of a function calls
the same function (called ‘circular definition’)
return_type function_name()
{
// code to be executed
function_name(): // calling same function
}
Recursion
Example: Write a program that computes factorial of a number.
n! = n * (n-1)! {
int a, fact ;
0! =1 Factorial Function : Base Criteria is
main( )
printf ( "\nEnter any number " ) ; scanf ( "%d", &a ) f = x * rec ( x - 1 );
; return ( f ) ;
}
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ; }
rec (int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
Enter any number 4 Factorial value = 24
Add functions to the Library (1)
Write the function definition of factorial() in some file, say ‘fact.c’.
int factorial ( int num )
{
int i, f = 1 ; return ( f ) ;
for ( i = 1 ; i <= num ; i++ ) f = f * i ; }
User Defined Function
(2) To use the function present inside the library, create a program
#include “fact.c”
#include <stdio.h>
main( )
{
int f ;
f = factorial ( 5 ) ;
printf ( “The factorial %d is", f ) ;
}
Practical
Write a function to find the Fibonacci numbers are
generated by the sequence. In a Fibonacci sequence the
sum of two successive terms gives the third term.
Following sequence: Fibonacci
are the first few terms of the
1 1 2 3 5 8 13 21 34 55 89 …….
Practical
Write a function to find the Fibonacci numbers are
generated by the sequence. In a Fibonacci sequence the
sum of two successive terms gives the third term.
Following sequence: Fibonacci
are the first few terms of the
1 1 2 3 5 8 13 21 34 55 89 …….
int f=1, s=1, t, i;
for(i=3; i<=n; i++)
{
t = f + s;
f = s;
s = t;
}
int f=1, s=1, t, i;
Practical printf("%d\t", f);
printf("%d\t", s);
main() for(i=3; i<=n; i++)
{ {
int n; t = f+s;
printf("Enter how many numbers\n"); printf("%d\t", t);
scanf("%d", &n); f = s;
fibo(n); s = t;
}
} }
fibo(int n)
{
main() }
{ fibo(int n)
int n,i=1, c; {
printf("Enter any number\n"); scanf("%d", &n); if(n==0)
for(c=1; c<=n; c++) return 0;
{ else if(n==1)
printf("%d\t", fibo(i)); return 1;
i++; else
} return(fibo(n-1) + fibo(n-2)); }
Assignment
• Write a program to input two numbers and then display the
following menu using functions:
- sum of two numbers
- subtract the second number from the first
- multiply the two number
- divide the first number by the second
- none of the above
The program will then produce the output selected by the user
from the menu.
Pointers
Introduction to Pointers
• A pointer refers to a memory location that contains an address.
• The C programming language provides a special mechanism for
passing variables to functions that is a little unintuitive, but
extremely powerful.
• C provides two operators, & and *, which allow you to pass a
variable instead of its value.
Pointers
Introduction to Pointers
• A pointer must be declared and the variable type it points to
must be specified.
int *ptr;
• Address Operator (&) : An address is assigned to a pointer using
the address operator.
prt_v = &x;
• Indirection Operator (*): A value is assigned to a variable it
points to using the indirection operator.
*ptr_v = 77;
Pointer Notation
• Consider the declaration
int i = 3;
(a) Reserve space in memory to hold the integer value
(b) Associate the name i with this memory location (c)
Store the value 3 at this location
#include <stdio.h>
Example
main()
{ Note:
int i =3;
printf(“\n Address of i= %u”, &i); *(&i) = i = value of the variable
printf(“\n Value of i = %d”, i);
printf(“\n Value of i = %d”, *(&i); }
Output
Address of i = 2293572
Value of i = 3
Value of I = 3
Example
&i
*j
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of j =
%u", &j ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of
i = %d", *( &i ) ) ; printf ( "\nValue of i = %d", *j ) ; }
Example
&i
*j
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of j =
%u", &j ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of
i = %d", *( &i ) ) ; printf ( "\nValue of i = %d", *j ) ; }
Output:
Address of i = 65524 Address of i = 65524 Address of j = 65522 Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3
Example
main( )
k is a pointer to an integer pointer
{
int i = 3, *j, **k ;
j = &i ;
k = &j ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of i = %u", *k ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nAddress of j = %u", k ) ;
printf ( "\nAddress of k = %u", &k ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of k = %u", k ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", * ( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
printf ( "\nValue of i = %d", **k ) ;
Example
main( )
k is a pointer to an integer pointer );
{
printf ( "\nValue of i = %d", **k ) ;
int i = 3, *j, **k ;
j = &i ;
k = &j ;
printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", Output:
j);
Address of i = 65524 Address of i = 65524
printf ( "\nAddress of i = %u", *k ) ; printf ( "\nAddress of j = %u",
Address of i = 65524 Address of j = 65522
&j ) ; printf ( "\nAddress of j = %u", k ) ;
Address of j = 65522 Address of k = 65520
printf ( "\nAddress of k = %u", &k ) ; printf ( "\nValue of j = %u", j ) ;
Value of j = 65524
printf ( "\nValue of k = %u", k ) ; Value of k = 65522 Value of i = 3
printf ( "\nValue of i = %d", i ) ;
Value of i = 3
printf ( "\nValue of i = %d", * ( &i ) ) ; printf ( "\nValue of i = %d", *j
Value of i = 3 Value of i = 3
Limitations of Pointers
• If memory allocations are not free properly it can cause
memory leakages
• If not used properly can make the program difficult to
understand
Exercises
1. Write a function to obtain the running sum of first 25 natural
numbers.
2. Write a function which receives a float and an int from main( ),
finds the product of these two and returns the product which is
printed through main( ).
3. Write a function that receives 5 integers and returns the sum,
average and standard deviation of these numbers. Call this
function from main( ) and print the results in main( ).
Exercises
4. Write a function power ( a, b ), to calculate the value of a
raised to b.
5. Write a function to calculate the factorial value of any integer
entered through the keyboard.
Summary
• A function can be called either by value or by reference •
Pointer can be used to make a function return more than one
value simultaneously.
• Recursion is difficult to understand , but in some cases offer a
better solution than loops.
• Adding too many functions and calling them frequently may
shut down the program execution.