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

Lect 14 17 Functions

Uploaded by

abhiramnambi2006
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lect 14 17 Functions

Uploaded by

abhiramnambi2006
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

Functions

INTRODUCTION

•Strength of ‘C’ language is C functions

•They are easy to define and use

•We are very much familiar with main(), printf() & scanf()
function
Function:

•A set of statements working together with common goal is


known as function.

•Also known as subprograms which we use to compute a


value or perform a specific task.

•They can’t run independently and are always called by the


main() program or by some other function.
Categories of functions

•Library functions /Built-in

•scanf(), printf(), getch(), strlen(), strcmp(), strcat(), sqrt(), pow()


are this are library functions.

•User-Defined functions

•main() is user-defined functions


User Defined Functions

•User defined functions are self-contained blocks of statements


which are written by the user to compute or perform a task.

•They can be called by the main program repeatedly as per the


requirement.
Uses of functions
•They are very much useful when a block of statements has to
be written/executed again and again.

•They are useful when program size is too large and complex.

•It works like top-down modular programming technique to


solve a problem.

•They are also used to reduce the difficulties during


debugging a program.
•The length of a source program can be reduced by using
functions at appropriate places.

•.It is easy to locate and isolate a faulty function for further


investigations.

•.A function can be used by many other programs.

•Thus C programmer can build their own library.


Top-down modular programming using functions

Main Program

Function A Function B Function C

B1 B2
#include<stdio.h> Example
int add(int x, int y); // with out functions
int main()
{ int main()
add(); {
return 0; int num1, num2, res;
} printf("\nAdd First Number:\t");
scanf("%d", &num1);
int add()
{ printf("\nAdd Second Number:\t");
int num1, num2, sum; scanf("%d", &num2);
printf("\nAdd First Number:\t");
scanf("%d", &num1); res = num1+num2;
printf("\nAdd Second Number:\t");
printf("\nsum of Two Nums: %d", res);
scanf("%d", &num2); printf("\n");
sum = num1 + num2; return 0;
printf("\nAddition of Two Numbers: %d", sum); }
}
ELEMENTS OF USER DEFINED FUNCTION
Some similarities between functions and variables
• Both functions names and variables are considered
as identifiers and therefore they must follow the rules
for identifiers

• Like variables, functions have type(such as int)


associated with them

• Like variables, function names and their types must


be declared and defined before they are used in program
ELEMENTS OF USER DEFINED FUNCTION

• In order to make use of user-defined


functions, we need to establish three
elements that are related to functions.

Function definition
Function Call
Function declaration
Function Definition
• The function definition is an independent program
module that is specially written or implement the
requirements of the function.

• To use this block or function, we need to invoke it at


the required place in the program, known as the
functions

• The program that calls the function is referred to as


the calling function or called function.
main()
{
…..
function1();
….
….
function2();
}
function1()
{


}
function2()
{

function1();
}
Flow of function
• When the program is executed (that is, run) execution
always begins at the first statement in the function
main() no matter where it is placed in the program.

• Other functions are executed only when they are called.

• Function prototypes appear before any function


definition, so the compiler translates these first.

• The compiler can then correctly translate a function call.


• A function call statement results in the transfer of
control to the first statement in the body of the called
function.

• After the last statement of the called function is


executed, the control is passed back to the point
immediately following the function call.

• A value-returning function returns a value.

• Therefore, for value-returning functions, after


executing the function when the control goes back to
the caller, the value that the function returns replaces
the function call statement
Function definition
A function definition includes the following
elements
• Function name
• Function type
• List of parameters
• Local variable declarations
• Function statements
• a return statement
A general format of function definition

function_type function_name(parameter list) // function header


{
local variable declarations;
executable statement1;
executable statement2; // function body


return statement; //returns the value( optional )
}
• If no return data type is specified than by default
‘C’ will assume that it is an integer type.

• If the function is not going to return any value


then we have to specify the return type as void.

• Function name follows the rules of identifier


Formal Parameter list
• Parameter list declare the variables that will
receive the data sent by the calling program.

int sum(int a, int b) { ………………… }


float mul(float x, float y) { ………………. }
Calling a function

• A function is called by the calling program


using the function name with the required
number of arguments in parenthesis.

• The function call comes in assignment


statement or in an output statement.

printf(“%d”,sum(a,b));
ans = sum(a,b);
Formal and Actual Arguments
int sum(int, int); //declaration

void main()
{
int a=5, b=6,ans;
ans =sum(a , b); //calling function
printf(“Answer : %d”,ans);
}
//function definition
int sum(int x, int y)
{
int val;
val = x +y;
return val;
}
Actual arguments
• The arguments listed in the function calling
statement are referred to as actual arguments.

• The parameters that are used in function calls


are called actual parameters.

• They are the actual values passed to a function


to compute a value or to perform a task.
Formal arguments
• The arguments used in the function declaration
and function definition are referred as formal
arguments.

• They are simply formal variables that accepts or


receive the values supplied by the calling
program.
Rules of calling a function
• Function is called by the main() or any other function

• When the return type of the function is omitted, then


by default the return type will be int.
• A function can return a value at any stage of its
execution by using more than one return statements.
• The return statement is omitted if it does not return a
value directly to the calling program.
• Arguments listed can be omitted, but not the
parenthesis () following the function.
Function Declaration or Function prototype
• All functions in c program must be declared, before they are
invoked.
• Function declaration consist of 4 parts

1. Function type
2. Function name
3. Parameter list
4. Termination semicolon
syntax

• function_type function_name(parameter list);

Example
int sum(int, int);
• The prototype declaration is always written
above the main() function definition.
Return values and their types
• We can pass n numbers of values to the called
function, but the called function can only
return one value per call.
• The return statement can take one of the
following form

return;
(or)
return(expression);
• The plain return does not return any value

• return statement with expression returns the


value of the expression

• There can be more than one return statement


if there is use of conditional statement.
• When a function reaches a return statement ,
the control is transferred back to the calling
program.
• In the absence of return statement, closing
brace acts as void return.

• A local variable is a variable that is defined


inside a function and used without having any
role of communication between functions.
Categories of functions
1. Functions with no arguments and no return values
2. Functions with arguments and no return values
3. Functions with arguments and one return value
4. Functions with no arguments but a return value
5. Functions that return multiple values
Functions with no arguments and no return values
• #include <stdio.h>
• void sum(); // function declaration

• void sum() // function definition


• {
• int a,b,result=0;
• printf("Enter the value of a\n");
• scanf("%d",&a);
• printf("Enter the value of b\n");
• scanf("%d",&b);
• result=a+b;
• printf(" Inside function the sum of two no is:%d",result);
• }
• int main() {

• printf("This is a function with no args & no return\n");
• sum(); // function call

• return 0;
• }
Functions with arguments and no return values
• #include <stdio.h>
• void sum(int x,int y); // function declaration

• void sum(int x,int y) // function definition


• {
• int result=0;
• result=x+y;
• printf(" Inside function the sum of two no is:%d",result);
• }
• int main() {
• int a,b;
• printf("Enter the value of a\n");
• scanf("%d",&a);
• printf("Enter the value of b\n");
• scanf("%d",&b);
• printf("This is a function with args & no return\n");
• sum(a,b); // function call

• return 0;
• }
Functions with arguments and one return value
• #include <stdio.h>
• int sum(int x,int y); // function declaration
• int sum(int x,int y) // function definition
• {
• int result=0;
• result=x+y;
• return result;
• }
• int main() {
• int a,b,final=0;
• printf("Enter the value of a\n");
• scanf("%d",&a);
• printf("Enter the value of b\n");
• scanf("%d",&b);
• printf("This is a function with args & one return\n");
• final=sum(a,b); // function call

• printf(" Inside main function the sum of two no is:%d",final);
• return 0;
• }
Functions with no arguments but a return value

• #include <stdio.h>
• int sum(); // function declaration

• int sum() // function definition


• {
• int x,y,result=0;
• printf("Enter the value of x\n");
• scanf("%d",&x);
• printf("Enter the value of y\n");
• scanf("%d",&y);
• result=x+y;
• return result;
• }


• int main() {
• int final=sum(); // function call

• printf(" Inside main function the sum of two no is:%d",sum()); return 0;
• }
Call By Value & Call By Reference
• Both are parameters passing methods.
• The parameters of functions can be passed in two ways:
• Call by value: A copy of the variable is passed to the
function.
• Call by reference: An address of the variable is passed to
the function.
Example- Call by Value
• #include<stdio.h>
• void swap(int n1, int n2)
• {
• int temp = n1;
• n1 = n2;
• n2 = temp;
• }

int main() {
int x = 20;
int y = 68;
printf("The numbers before swapping n1 and n2 %d %d \n",x, y);
swap(x, y);
printf("The numbers after swapping n1 and n2 %d %d \n",x, y);
return 0;
}
Call by Reference
• #include<stdio.h>
• void swap(int *n1 ,int *n2)
• {
• int temp = *n1;
• *n1 = *n2;
• *n2 = temp;

• }
int main() {
int n1 = 20;
int n2 = 68;
printf("The numbers before swapping n1 and n2 %d %d \n",n1, n2);
swap(&n1, &n2);
printf("The numbers after swapping n1 and n2 %d %d",n1, n2);
return 0;
}
C program to swap two numbers using functions
S.no C function syntax

int function ( int ); // function declaration


function ( a ); // function call
int function( int a ) // function definition
with arguments and with
1 {
return values
statements;
return a;
}
void function ( int ); // function declaration
function( a ); // function call
with arguments and without void function( int a ) // function definition
2
return values {
statements;
}
void function(); // function declaration
function(); // function call
without arguments and without void function() // function definition
3
return values {
statements;
}
int function ( ); // function declaration
function ( ); // function call
int function( ) // function definition
without arguments and with
4 {
return values
statements;
return a;
}
Return multiple values from a function
Passing arrays to functions

• No direct approach.

The methods to return multiple values from a


function in C:
• By using pointers.
• By using structures.
• By using Arrays.
Swap two numbers with no parameter and multiple return values

#include <stdio.h>
void swap(int arr[])//Empty array
void swap(int arr[]);
{
int main()
int x=5,y=10,temp;
{
int arr[2];
temp=x;
swap(arr);
x=y;
printf("%d",arr[0]);
y=temp;
printf("%d",arr[1]);
return 0;
arr[0]=x;
}
arr[1]=y;

}
Swap two numbers with parameter and multiple return values

• #include <stdio.h>
• void swap(int arr[]);
• int main()
• {
void swap(int arr[])// array with values
• int arr[2]={1,2}; {
• swap(arr); int temp;
• printf("%d",arr[0]); temp=arr[0];
• printf("%d",arr[1]); arr[0]=arr[1];
• return 0; arr[1]=temp;
• } }
Passing Arrays to Functions
• Passing individual elements of an array.
• Passing entire array to a function.
// Passing individual Array Elements // Passing Complete Array
#include <stdio.h>
void printarrfn (int x,int y); #include <stdio.h>
int main() void printarrfn(int a[]);
{ int main()
int arr[5]={10,20,3,40,5}; {
int arr[5]={10,20,3,40,5};
printarrfn(arr[0],arr[4]);
printarrfn(arr);
}
}
void printarrfn(int x,int y)
{ void printarrfn(int a[])
printf("0th index:%d\n4th Index {
%d",x,y); for(int i=0;i<5;i++)
}
{
printf("%d\n",a[i]);
}
}
Recursive Function
• A function that calls itself is known as a recursive function. And,
this technique is known as recursion.

void function1()
{
... .. ...
function1();
... .. ...
}
int main()
{
... .. ...
function1();
... .. ...
}
Example: Sum of Natural Numbers Using Recursion
• #include <stdio.h>
int sum(int n) {
• int sum(int n);
if (n != 0)
// sum() function calls itself
• int main() { return n + sum(n-1);
• int number, result; else
return n;
• printf("Enter a positive integer: "); }
• scanf("%d", &number);

• result = sum(number);

• printf("sum = %d", result);


• return 0;
• }

You might also like