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

Lecture User Defined Functions

The document discusses user-defined functions in C programming. It covers defining functions with parameters, return types, and return values. It also discusses dividing programs into smaller modular functions to organize code. The key points are: 1) Functions are a way to divide programs into smaller, reusable modules called functions. This organizes code and makes it more manageable. 2) Functions are defined with a return type, name, and parameters. They can take in arguments, perform operations, and return values. 3) Functions are called from other parts of a program and code is passed between the calling function and called function. Arguments are passed in and return values come out.

Uploaded by

Home Tv
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

Lecture User Defined Functions

The document discusses user-defined functions in C programming. It covers defining functions with parameters, return types, and return values. It also discusses dividing programs into smaller modular functions to organize code. The key points are: 1) Functions are a way to divide programs into smaller, reusable modules called functions. This organizes code and makes it more manageable. 2) Functions are defined with a return type, name, and parameters. They can take in arguments, perform operations, and return values. 3) Functions are called from other parts of a program and code is passed between the calling function and called function. Arguments are passed in and return values come out.

Uploaded by

Home Tv
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/ 33

CSE109

User defined functions(Introduction to


Functions)
Parameter Passing mechanisms(Call by value
and Call by reference)

©LPU CSE101 C Programming


Functions

©LPU CSE101 C Programming


Divide and Conquer
• Best way to solve a problem is by dividing the
problem and solving it.
• Divide and conquer
– Construct a program from smaller pieces or
components
• These smaller pieces are called modules
– Each module more manageable than the original
program

©LPU CSE101 C Programming


Program Modules in C
Hierarchical boss function/worker function relationship.

©LPU CSE101 C Programming


Program Modules in C
• Functions
– Modules in C are called functions.
– Two categories of functions: Pre-defined(or library
functions) and User defined
– Programs combine user-defined functions with library
functions
• C standard library has a wide variety of functions for
performing common mathematical calculations, string
manipulations, character manipulations, input/output and
many more.
• C standard library makes your job easier.
• Functions like printf(), scanf(), pow() are standard library
functions.
• We can also write functions to define some specific task in a
program and these functions are called user-defined
functions.

©LPU CSE101 C Programming


What are functions??
• Functions
• A function is a set of statements that take inputs, do some
specific computation and produces output.
• 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.

©LPU CSE101 C Programming


Benefits of functions
• 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.

©LPU CSE101 C Programming


Three important parts/ or components of any user
defined function

• Function declaration/ or Function prototype/


or Function signature
• Function definition
• Function calling

©LPU CSE101 C Programming


Function declaration/ or Function prototype/ or
Function signature

• A function declaration tells the compiler about the number of parameters


function takes, data-types of parameters and return type of function.
Putting parameter names in function declaration is optional in the function
declaration, but it is necessary to put them in the definition. Below are an
example of function declarations. (parameter names are not there in
below declarations)
Syntax:
return_type function_name( parameter list/or arguments );
Example 1:
int example(int,int);// Here function is returning integer value and accepting
two integer arguments
Example 2:
void example();// Here function is returning nothing and it is accepting no
argument

©LPU CSE101 C Programming


Function definition
• Function definition consists of the set of
statements that are required to be executed
when the function is used.
• It consists of body of the function along with
function header
• Function header is same as function
declaration but there is no semicolon after it
• Function header is followed by function body
where actual functionality of the function is
placed
©LPU CSE101 C Programming
Function definition-Example
Syntax:
return_type function_name( parameter list ) //Function Header
{
//body of the function // Function body
}
Example:
int sum(int x,int y) // sum is a user defined function which takes two integer parameters
{
int z;
z=x+y;
return z; //After adding two integers it is returning the result
}

©LPU CSE101 C Programming


Function Calling
• Once the function is declared and defined, we wish to use it.
So, for using the function we need to call it
• When the function is called in the main() function/ or some
other function, the control is transferred to the called
function, once the function definition is executed completely,
the control will come back to the main()/ or the other
function in which the calling statement has been placed, and
the execution will resume from the same point where it was
halted.
• Syntax of function calling:
function_name(<List_of_argument_values>);
Example: function(2,3);

©LPU CSE101 C Programming


Points to remember during function calling

• Function name and the number and type of arguments in the function call must be
same as that given in the function declaration and function header of the function
definition
• Names (and not the types) of variables in function declaration, function call and
header of function definition may vary
• Arguments may be passed in the form of expressions to the called function. In such
a case, arguments are first evaluated and converted to the type of formal
parameter and then the body of the function gets executed.
• If the return type of the function is not void, then the value returned by the called
function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, …);

©LPU CSE101 C Programming


Program example of function
#include<stdio.h> // FUNCTION DEFNITION
int sum(int a, int b);// FUNCTION DECLARATION int sum ( int a, int b)// FUNCTION HEADER
int main() {
{ // FUNCTION BODY
int num1, num2, total = 0; return (a + b);
printf(“\n Enter the first number : “); }
scanf(“%d”, &num1);
printf(“\n Enter the second number : “);
scanf(“%d”, &num2);
total = sum(num1, num2); //
FUNCTION CALL
printf(“\n Total = %d”, total);
return 0;
}

©LPU CSE101 C Programming


return statement in functions
• The return statement is used to terminate the execution of a function and return control to
the calling function. When the return statement is encountered, the program execution
resumes in the calling function at the point immediately following the function call.
• Calling function is one in which the function is called(usually main()), and the called function
is one whose definition is placed outside main() or/ some other function
• A return statement returns a value to the calling function. The syntax of return statement can
be given as
return <expression> ;
• Here expression is placed in between angular brackets because specifying an expression is
optional. The value of expression, if present, is returned to the calling function. However, in
case expression is omitted, the return value of the function is undefined.
• Programmer may or may not place the expression within parentheses.
• For functions that has no return statement, the control automatically returns to the calling
function after the last statement of the called function is executed.

©LPU CSE101 C Programming


Types of user defined functions
1) Function with no argument and no return value :When a function has
no arguments, it does not receive any data from the calling function.
Similarly when it does not return a value, the calling function does not
receive any data from the called function. (input, output statements and
actual logic ,all will be placed in the function definition)
2) Function with arguments but no return value : When a function has
arguments, it receive data from the calling function but it returns no
values.(input will be taken in the calling function, whereas output
statement and logic will be placed in the function definition)
3) Function with no arguments but returns a value : There could be
occasions where we may need to design functions that may not take any
arguments but returns a value to the calling function. (input statement
and logic will be placed in function definition and output statement will
be placed in calling function)
4) Function with arguments and return value: This kind of function returns
a value as well as it can accept arguments also.(input and output
statements will be placed in calling function and logic will be placed in
function definition)
©LPU CSE101 C Programming
Program example: Function with no argument and no return value
Write a program to add two numbers using function with no argument and no
return value
#include<stdio.h>
void add(); //Function declaration • Here input, output
int main() statements and logic all are
{ placed in the function
add(); //Function calling
return 0;
definition
}
//Function definition
void add()
{
int a,b,sum;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
sum=a+b;
printf("\n Sum of two numbers is:%d",sum);
}

©LPU CSE101 C Programming


Program example: Function with arguments but no return value
Write a program to add two numbers using function with argument but no
return value
#include<stdio.h> • Here input is taken in calling
void add(int,int); //Function declaration
function(i.e. main())
int main()
{ whereas output statement
int a,b; and logic is placed in the
printf("\n Enter two numbers:"); function definition
scanf("%d%d",&a,&b);
add(a,b); //Function calling //a, b are actual arguments • Note: Arguments in function
return 0; call statements are actual
} arguments, whereas
//Function definition
void add(int x,int y) //x and y are formal arguments
arguments in function
{ definition are formal
int sum; arguments
sum=x+y;
printf("\n Sum of two numbers is:%d",sum);
}

©LPU CSE101 C Programming


Program example: Function with no arguments but returns a value
Write a program to add two numbers using function no arguments but return
a value
#include<stdio.h>
int add(); //Function declaration • Here input statement
int main()
{
and logic is placed in
int result; the function definition
result=add(); //Function calling
printf("\n Sum is:%d",result); and then it returns sum,
return 0;
}
and output statement is
//Function definition written in the calling
int add()
{ function(i.e. main())
int a,b,sum;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
sum=a+b;
return sum;
}

©LPU CSE101 C Programming


Program example: Function with arguments and return value
Write a program to add two numbers using function with arguments and
return a value
#include<stdio.h>
int add(int,int); //Function declaration • Here input and output
int main()
{
statements are placed
int a,b,result; in the calling function
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b); (i.e. main()) and logic is
result=add(a,b); //Function calling //a, b are actual arguments
printf("\n Sum is:%d",result);
placed in the function
return 0; definition
}
//Function definition • Note: Arguments in
int add(int x,int y) //x and y are formal arguments
{ function call statements
int sum;
sum=x+y; are actual arguments,
return sum;
}
whereas arguments in
function definition are
formal arguments
©LPU CSE101 C Programming
Parameter Passing mechanisms in C/ or Argument Passing
techniques in C/ or Calling mechanisms in C

There are two ways in which arguments or parameters can be


passed to the called function.
•Call by value in which values of the variables are passed by the
calling function to the called function.
•Call by reference in which address of the variables are passed
by the calling function to the called function

©LPU CSE101 C Programming


Call by value
• In the Call by Value method, 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.
#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);
}
The output of this program is:
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

©LPU CSE101 C Programming


Advantages and Disadvantages of Call by value

Advantages:
•The method doesn't change the original variable, so it is preserving data.
•Whenever a function is called it, never affect the actual contents of the
actual arguments.
•The other advantage could be arguments can be variables(e.g. x), literals(e.g.
6,0…), or expressions(e.g. x+1)
Disadvantages:
•Copy of the variable is created hence it can consume additional storage
space
•Along with more space, it can take a lot of time to copy, thereby resulting in
performance penalty, especially if the function is called many times

©LPU CSE101 C Programming


Call by reference
• When the calling function passes arguments to the called function using call by
value method, the only way to return the modified value of the argument to the
caller is explicitly using the return statement. The better option when a function
can modify the value of the argument is to pass arguments using call by reference
technique.
• In call by reference, we declare the function parameters as pointers rather than
normal variables. When this is done, any changes made by the function to the
arguments ,are visible to the calling program.
• To indicate that an argument is passed using call by reference, address of the
variable is passed as an actual argument during function calling, and pointers will
act as formal arguments in the function definition to which the addresses will be
assigned

©LPU CSE101 C Programming


Call by reference(Program example)
#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);
}
The output of this program is:
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

©LPU CSE101 C Programming


Advantages and Disadvantages of Call by reference

Advantages:
•It provides greater time and space efficiency as duplicate copies of the
arguments are not created
•In this method, there is no copy of the argument made. Therefore it is
processed very fast.
Disadvantages:
•Original values are not safe, as they can be modified
•We can only pass addresses as actual arguments(we cannot pass:
literals(1,2,3…) / or expressions(x+1,y+2..) as actual arguments

©LPU CSE101 C Programming


Call by value vs Call by reference
Parameters Call by value Call by reference

While calling a function, in


programming language instead of
While calling a function, when you
copying the values of variables,
Definition pass values by copying variables, it
the address of the variables is
is known as "Call By Values."
used it is known as "Call By
References.

In this method, a copy of the In this method, address of the


Arguments
variable is passed. variable is passed.

Changes made in a copy of Change in the variable also affects


Effect variable never modify the value of the value of the variable outside
variable outside the function. the function.

Allows you to make changes in the


Does not allow you to make any
Alteration of value values of variables by using
changes in the actual variables.
function calls.

Values of variables are passed Pointer variables are required to


Passing of variable
using a straightforward method. store the address of variables.

Value modification Original value not modified. The original value is modified.

©LPU CSE101 C Programming


Q1
Which of the following is a correct format for
declaration of function?
A. return-type function-name(argument type);
B. return-type function-name(argument type){}
C. return-type (argument type)function-name;
D. all of the mentioned

©LPU CSE101 C Programming


Q2
Which function definition will run correctly?
a) int sum(int a, int b)
return (a + b);
b) int sum(int a, int b)
{return (a + b);}
c) int sum(a, b)
return (a + b);
d) none of the mentioned

©LPU CSE101 C Programming


Q3
Which of the following is a valid function
declaration statement?
A.function1(int,int);
B.void function1(a,b);
C.void 1function(int,int);
D.void function1(int,int);

©LPU CSE101 C Programming


Q4
Which of the following is a valid function call
statement for user defined function: abc
a) abc(int);
b) void abc();
c) abc();
d) int abc(int);

©LPU CSE101 C Programming


Q5
What will be the output of the A. hi
following C code?
B. Run time error
#include <stdio.h>
void m()
C. Nothing will be displayed
{ D. Compile time error
printf("hi");
}
int main()
{
m();
return 0;
}

©LPU CSE101 C Programming


Q6
What will be the output of the
following C code? A. Compile time error
#include <stdio.h> B. hi
void m();
C. Infinite hi
int main()
{ D. Nothing
m();
return 0;
}
void m()
{
printf("hi");
m();
}

©LPU CSE101 C Programming

You might also like