SlideShare a Scribd company logo
1 of 37
Programming in C & C++
Functions in C
&
Functions in C++
Submitted by,
M. Kavitha M.Sc.,
N.S.College of Art & Science,
Programming in C
Functions
Synopsis :
1. Function
2. User – defined function
3. Need for user – defined function
4. Element of user – defined function
5. Category of function
6. Nested function
7. Recursion function
Functions in C :
* Function is a smallest building black of a program. It
is a part of the program.
* C function can be classified into two categories of
function,
* Library function printf ( ), scanf ( )
* user – defined function main( )
Library function :
* printf and scanf belong to the category of function
and it is a default function known as the library function.
Example :
printf (“n Welcome”);
scanf (“%d”,&);
* It is also used other library function such as sqrt, cos,
strcat, etc.,
User – defined Function :
A user – defined function has to be developed by the
user at the time of writing a program.
It is used to main( ) user – defined function can later
become a part of the C program library.
Example :
main( )
{
int a=30,b=10,c;
c= a+b;
printf(“n the addition is:%d”,c);
}
Need for User – Defined Function :
The program may become too large and complex and as
a result the task of debugging, testing and maintaining becomes
difficult.
Advantages :
* It facilitates top – down modular program.
* The length of a source program can be reduced by
using function.
* It is easy to locate and isolate a faulty function.
* A function may be used by many other program.
Main Program
Function
A
Function
B
Function
C
B1 B2
Element of User – defined function :
* Function names and variable names are considered
identifiers and therefore they must adhere to rules
identifiers.
* Variables, function have type associated with them.
* Variables, function names and their types must be
declared and defined before they are used in a program.
There are three element of user – defined function :
* Function Definition.
* Function Call.
* Function Declaration.
* The function definition is an independent program
module that is specially to implementation requirements of the
function.
* This function it at a required place in the program. This
is known as the function call.
* The program or a function that calls the function is
referred to as the calling program or calling function.
* The calling program declare any function like
declaration of a variable that is to be used in the program it is
known as function declaration or function prototype.
Definition of Function :
* function name * local variable declaration
* function type * function statement and
* list of parameters * a return statement
The six element are grouped into two parts,
* Function Header (First three element).
* Function Body (Second three element).
Syntax : Example :
Function _type function_name (parameter list)
{
local variable declaration;
executable statement 1;
executable statement 1;
.……….
………..
Return statement;
}
Function
Header
float mul ( float x, float y);
{
float result;
result = x*y;
return (result);
}
Function
Body
Function Calls :
A function can be called by simply using the function
name by a list of actual parameters or arguments.
Example :
Function Declaration :
A function declaration also known as function
prototype. Syntax : (int mul (int m, int n));
* Function type. * Parameter list.
* Function name. * Terminating semicolon.
main( )
{
int y;
y = mul (10,5);
printf(“%dn”,y);
}
function call
Category of Function :
A function depending on whether arguments are
present or not and whether a value is returned or not values.
1. Function with no arguments and no return type.
2. Function with arguments and no return type.
3. Function with arguments and one return type.
4. Function with no arguments but return type.
5. Function that return multiple values.
Syntax :
int show( );
main( )
{
….
show( );
}
int show( )
{
….….
}
function declaration
function call
function definition
No Arguments and No Return Values :
* A function has no arguments it does not receive any data
from the calling function.
* Similarly it does not return a value, the calling function
does not receiver any data from the called function.
* There is no data transfer between the calling function
and the called function.
function 1 ( )
{
……..
……..
function 2 ( )
.……
........
}
function 2 ( )
{
…………
………….
…………
…………
}
control
control
No input
No output
Example :
#include <stdio.h>
int area( );
int main( )
{
area ( );
}
int area( )
{
float area_circle;
float r;
printf(“n Enter the radius:”);
scanf(“%f”,&r);
area_circle=3.14*r*r;
printf(“n Area of circle
:%f”,area_circle);
}
Output:
Enter the radius : 5
Area of circle : 78.50000
1. No argument and no return value
No argument
No return value
Argument but No return values:
* The main function has no control over the way the
function receiver input data.
* For example, the function printline will print the same
line each time it is called same is the case with the function
value.
* The nature of data communication between the calling
function and the called function with argument but no return
value.
function 1 ( )
{
……..
……..
function 2 ( a)
.……
........
}
function 2 ( f)
{
…………
………….
…………
…………
}
Values of
argument
No return
value
Example :
#include <stdio.h>
int area(float r);
int main( )
{
float r;
printf(“n Enter the radius:”);
scanf(“%f”,&r);
area (r);
}
int area(float r)
{
float ar;
ar =3.14*r*r;
printf(“n Area of circle:%f”,ar);
}
Output:
Enter the radius : 2
Area of circle : 12.56000
2. Function with argument and no return value
Argument passing
No return value
Actual argument and Formal argument :
* The actual and formal arguments should match in
number, type, and order.
* The values of actual arguments are assigned to the
formal arguments on a one to one basis, starting with the first
argument.
main( )
(
……… (actual argument)
function 1 (a1,a2….,am);
………..
}
function 1 (f1,f1,…..,fn);
{ (formal argument)
………
……….
}
Function call
Called function
Argument with return values:
* The function value receives data from the calling
function argument, but does not send back any value.
* For example, the different programs may require
generally be coded without any I/O operation.
* A self-contained and independent function should
‘black box’ receives a predefined I/O desired value.
function 1 ( )
{
……..
……..
function 2 ( a)
.……
........
}
function 2 ( f)
{
…………
………….
…………
return(e);
}
Values of
argument
function
result
Example :
#include <stdio.h>
float square(float x);
int main( )
{
float m,n;
printf(“n The number of square:”);
scanf(“%f”,&m);
n= square(m);
printf(“n Square of the given
number:%f is %f”,m,n);
}
float square(float x)
{
float p;
p=x*x;
return(p);
}
Output:
The number of square: 4
Square of the given number
4.0000 is 16.0000
3. Function with argument but one return value
Argument passing
One return value
No Argument but Return a value:
* A function that any arguments but returns a value to
the calling function.
* A typical example is the getchar function declared in
the header file <stdio.h>.
* The getchar function has no parameters but it returns
an integer type data that represents a character.
int get_number(void);
int main( )
{
int m=get_number( );
printf(“%d”,m);
}
int get_number(void)
{
int number;
scanf(“%d”,&number);
return(number);
}
No Argument
Return a value
Function that return Multiple Value:
* A function that return just one value using a return
statement. That is because, a return statement can return only
one value.
* C using the arguments not only to receive information
but also to send back information to the calling function. The
arguments are used to ‘send out’ information are called output
parameters.
int math(int x, int y, int *s, int *d);
int main( )
{
int x=20,y=10,s,d;
Math(x,y,&s,&d);
printf(“n s=%dn d=%dn”,s,d);
}
int math(int a,int b,int *sum,int *diff)
{
*sum=a+b;
*diff=a-b;
}
Output
s=30
d=10
Multiple value
Nested of function :
Nesting of function freely. Main can call function1,
which calls function2, which calls function3,………….and so
on.
float ratio(int x, int y,int z);
int difference(int x,int y);
main( )
{
int a,b,c;
scanf(“%d %d %d”,&a,&b,&c);
printf(“%fn”,ratio(a,b,c));
}
float ratio(int x,int y,int z);
{
if(difference(y,z))
return(x/(y-z));
else
return(0.0);
}
int difference(int p,int q)
{
if(p!=q)
return(1);
else
return(0);
}
main( )
ratio( )
difference( )
Recursion :
* Recursion is a special case of this process, where a
function calls itself. A very simple example of recursion is
present in the function.
* A called function in turn calls another function a
process of ‘chaining’ occurs it used factorial function.
Example :
main( )
{
printf(“n programming in c”);
main( );
}
Programming in C++
Functions
Synopsis :
1. Introduction
2. Main function
3. Function prototyping
4. Call by reference
5. Return by reference
6. Inline function
7. Default arguments
8. Function Overloading
Introduction :
Dividing a program into functions is one of the major
principles of top-down, structured programming.
Advantage of using functions is that it is possible to
reduce the size of a program by calling and using them at
different places in the program.
Syntax :
int area( ); /* Function declaration */
main( )
{
…….
area( ); /* Function call */
}
int area( ) /* Function definition */
{
……
…… /* Function body */
}
Main Function :
* C does not specify any return type for the main( )
function which is the starting point for the execution of a
program.
main( )
{
// main program statement;
}
* The function that have a return value should use the
return statement for termination. The main ( ) function in C++
int main ( )
{
……. ( Function should return a value )
……..
return 0;
}
Function Prototyping :
* The prototype describe the function interface to the
compiler by giving details such as the number and type of
arguments and the type of return values.
* A function prototyping a template is always used when
declaring and defining a function.
* Function prototype is a declaration statement in the
calling program
Syntax :
type function_name (argument-list);
Example :
float volume(int x,float y,float z);
Call by Reference :
* A function call passes arguments by value. The called
function creates a new set of variables and copies the values of
arguments into them.
* Call by value method it used to value passes in
variables.
* The reference variable is a point to address in c++
permits to pass parameters to the function by reference.
* The ‘formal’ arguments in the called function become
to the ‘actual’ arguments in the calling function.
Syntax :
swap(a , b); swap(&a,&b);
(call-by-value) (call-by-reference)
Example : Call By Reference
#include<iostream.h>
int swap(int *a,int *b);
int main( )
{
int p=10,q=20;
cout<<“n before value p:%d q:%d”;
swap(&a,&b);
cout<<“n After the value p:%d q:%d”;
}
int swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
Output
Before value p:10 q:20
After the value p:10 q:20
Return by Reference :
* A function also return a reference.
For Example :
int & max(int &x,int &y)
{
if(x>y)
return x;
else
return y;
}
* Since the return type of max( ) is int &, the function
returns reference to x or y.
* Then a function call such as max(a,b) yield a reference
to either a or b depending on their values.
Inline Function :
* One of the objectives of using function in a program is to
save some memory space, which becomes appreciable when a
function is likely to be called many times.
* To eliminate the cost of calls to small functions, C++
propose a new feature called inline function.
* An inline function is a function that is expanded in line
when it is invoked.
Syntax : Example:
inline function-header
{
function boby
}
inline double cube (double a)
{
return(a*a*a);
}
* It is easy to make a function inline. To prefix the
keyword inline to the function definition. All inline functions
must be defined before they are called.
Example :
inline double cube(double a) { return (a*a*a); }
Inline expansion may not work are :
* For function returning values, if a loop, a switch or a
goto exists.
* Function not returning values, if a return statement
exists.
* If function contain static variables.
* If inline function are recursive.
Example for Inline Function program :
#include<iostream.h>
using namespace std;
inline float mul(float x,float y)
{
return (x*y);
}
inline double div(double p,double q)
{
return(p/q);
}
int main( )
{
float a=12.345,b=9.82;
cout<<mul(a,b)<<“n”;
cout<<div(a,b)<<“n”;
return 0;
}
Output
121.228
1.25713
Default Arguments :
* The function assigns a default value to the parameter
which does not have a matching argument in the function call.
* Default values are specified when the function is
declared.
Example :
float amount(float principal,int period, float rate=0.15);
* The default value is specified in a manner syntactically
similar to a variable initialization.
* The above prototype declares a default value of 0.15 to
the arguments rate.
* A default argument is checked for type at the time
of declaration and evaluated at the time of call.
* It provide a default value to a particular argument
in the middle of an argument list.
int mul(int i.int j=5,int k=10);
int mul(int i=5,int j);
int mul(int i=0,int j,int k=10);
int mul(int i=2,int j=5,int k=10);
* Default arguments are useful in situations where
some arguments always have the same value.
Example :
#include<iostream.h>
using namespace std;
int main( )
{
float amount;
float value(float p,int n,float
r=0.15);
void printline(char ch=‘*’,int
len=40);
printline( );
amount=value(5000.00,5);
cout<<“n final value:”;
printline(‘=‘);
return 0;
}
float value(float p,int n,float r)
{
int year=1;
float sum=p;
while(year<=n)
{
sum=sum*(1+r);
year=year+1;
}
return (sum);
}
void printline(char ch,int len)
{
for(int i=1;i<=len;i++)
printf(“%c”,ch);
printf(“n”);
}
Output :
**********************
Final value=10056.8
==================
Function Overloading :
* A function overloading refers to the use of the same
thing for different purposes.
* C++ also permits overloading of functions.
* This means that we can use the same function name to
create functions that performs a variety of different tasks.
* This is known as function polymorphism in OOP.
Example :
/* Declaration */ /* Function calls */
int add(int a,int b); cout<< add(5,10);
int add(int a,int b,int c); cout<< add(15,10.0);
double add(double x,double y); cout<< add(12.5,7.5);
double add(int p,double q); cout<< add(5,10,15);
double add(double p,int q); cout<< add(0.75,5);
Example :
#include<iostream.h>
using namespace std;
int volume(int);
double volume(double ,int );
long volume(long ,int ,int );
int main( )
{ cout<<volume(10)<<“n”;
cout<<volume(2.5,8)<<“n”;
cout<<volume(100L,75,15)<<“n”;
return 0; }
int volume(int s)
{ return(s*s*s);
}
double volume(double r ,int h) output:
{ return(3.14519*r*r*h); }
long volume(long l ,int b,int h) 1000
{ return(l*b*h); 157.26
} 112500
Thank You

More Related Content

What's hot

Inline function
Inline functionInline function
Inline function
Tech_MX
 

What's hot (20)

Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Inline function
Inline functionInline function
Inline function
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Recursion in C++
Recursion in C++Recursion in C++
Recursion in C++
 
Function
FunctionFunction
Function
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 

Similar to C and C++ functions

Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
alish sha
 

Similar to C and C++ functions (20)

Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
C functions list
C functions listC functions list
C functions list
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Functions
FunctionsFunctions
Functions
 
functions
functionsfunctions
functions
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Functions
FunctionsFunctions
Functions
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
Function
FunctionFunction
Function
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 

More from kavitha muneeshwaran (13)

Physical Security
Physical SecurityPhysical Security
Physical Security
 
Digital Audio
Digital AudioDigital Audio
Digital Audio
 
Java
JavaJava
Java
 
Data structure
Data structureData structure
Data structure
 
Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
 
Digital image processing
Digital image processing  Digital image processing
Digital image processing
 
Staffing level estimation
Staffing level estimation Staffing level estimation
Staffing level estimation
 
Data Integration and Transformation in Data mining
Data Integration and Transformation in Data miningData Integration and Transformation in Data mining
Data Integration and Transformation in Data mining
 
Transaction Management - Deadlock Handling
Transaction Management - Deadlock HandlingTransaction Management - Deadlock Handling
Transaction Management - Deadlock Handling
 
Process
ProcessProcess
Process
 
Digital Logic circuit
Digital Logic circuitDigital Logic circuit
Digital Logic circuit
 
I/O system in intel 80386 microcomputer architecture
I/O system in intel 80386 microcomputer architectureI/O system in intel 80386 microcomputer architecture
I/O system in intel 80386 microcomputer architecture
 
narrow Band ISDN
narrow Band ISDNnarrow Band ISDN
narrow Band ISDN
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 

C and C++ functions

  • 1. Programming in C & C++ Functions in C & Functions in C++ Submitted by, M. Kavitha M.Sc., N.S.College of Art & Science,
  • 2. Programming in C Functions Synopsis : 1. Function 2. User – defined function 3. Need for user – defined function 4. Element of user – defined function 5. Category of function 6. Nested function 7. Recursion function
  • 3. Functions in C : * Function is a smallest building black of a program. It is a part of the program. * C function can be classified into two categories of function, * Library function printf ( ), scanf ( ) * user – defined function main( ) Library function : * printf and scanf belong to the category of function and it is a default function known as the library function. Example : printf (“n Welcome”); scanf (“%d”,&); * It is also used other library function such as sqrt, cos, strcat, etc.,
  • 4. User – defined Function : A user – defined function has to be developed by the user at the time of writing a program. It is used to main( ) user – defined function can later become a part of the C program library. Example : main( ) { int a=30,b=10,c; c= a+b; printf(“n the addition is:%d”,c); } Need for User – Defined Function : The program may become too large and complex and as a result the task of debugging, testing and maintaining becomes difficult.
  • 5. Advantages : * It facilitates top – down modular program. * The length of a source program can be reduced by using function. * It is easy to locate and isolate a faulty function. * A function may be used by many other program. Main Program Function A Function B Function C B1 B2
  • 6. Element of User – defined function : * Function names and variable names are considered identifiers and therefore they must adhere to rules identifiers. * Variables, function have type associated with them. * Variables, function names and their types must be declared and defined before they are used in a program. There are three element of user – defined function : * Function Definition. * Function Call. * Function Declaration.
  • 7. * The function definition is an independent program module that is specially to implementation requirements of the function. * This function it at a required place in the program. This is known as the function call. * The program or a function that calls the function is referred to as the calling program or calling function. * The calling program declare any function like declaration of a variable that is to be used in the program it is known as function declaration or function prototype. Definition of Function : * function name * local variable declaration * function type * function statement and * list of parameters * a return statement
  • 8. The six element are grouped into two parts, * Function Header (First three element). * Function Body (Second three element). Syntax : Example : Function _type function_name (parameter list) { local variable declaration; executable statement 1; executable statement 1; .………. ……….. Return statement; } Function Header float mul ( float x, float y); { float result; result = x*y; return (result); } Function Body
  • 9. Function Calls : A function can be called by simply using the function name by a list of actual parameters or arguments. Example : Function Declaration : A function declaration also known as function prototype. Syntax : (int mul (int m, int n)); * Function type. * Parameter list. * Function name. * Terminating semicolon. main( ) { int y; y = mul (10,5); printf(“%dn”,y); } function call
  • 10. Category of Function : A function depending on whether arguments are present or not and whether a value is returned or not values. 1. Function with no arguments and no return type. 2. Function with arguments and no return type. 3. Function with arguments and one return type. 4. Function with no arguments but return type. 5. Function that return multiple values. Syntax : int show( ); main( ) { …. show( ); } int show( ) { ….…. } function declaration function call function definition
  • 11. No Arguments and No Return Values : * A function has no arguments it does not receive any data from the calling function. * Similarly it does not return a value, the calling function does not receiver any data from the called function. * There is no data transfer between the calling function and the called function. function 1 ( ) { …….. …….. function 2 ( ) .…… ........ } function 2 ( ) { ………… …………. ………… ………… } control control No input No output
  • 12. Example : #include <stdio.h> int area( ); int main( ) { area ( ); } int area( ) { float area_circle; float r; printf(“n Enter the radius:”); scanf(“%f”,&r); area_circle=3.14*r*r; printf(“n Area of circle :%f”,area_circle); } Output: Enter the radius : 5 Area of circle : 78.50000 1. No argument and no return value No argument No return value
  • 13. Argument but No return values: * The main function has no control over the way the function receiver input data. * For example, the function printline will print the same line each time it is called same is the case with the function value. * The nature of data communication between the calling function and the called function with argument but no return value. function 1 ( ) { …….. …….. function 2 ( a) .…… ........ } function 2 ( f) { ………… …………. ………… ………… } Values of argument No return value
  • 14. Example : #include <stdio.h> int area(float r); int main( ) { float r; printf(“n Enter the radius:”); scanf(“%f”,&r); area (r); } int area(float r) { float ar; ar =3.14*r*r; printf(“n Area of circle:%f”,ar); } Output: Enter the radius : 2 Area of circle : 12.56000 2. Function with argument and no return value Argument passing No return value
  • 15. Actual argument and Formal argument : * The actual and formal arguments should match in number, type, and order. * The values of actual arguments are assigned to the formal arguments on a one to one basis, starting with the first argument. main( ) ( ……… (actual argument) function 1 (a1,a2….,am); ……….. } function 1 (f1,f1,…..,fn); { (formal argument) ……… ………. } Function call Called function
  • 16. Argument with return values: * The function value receives data from the calling function argument, but does not send back any value. * For example, the different programs may require generally be coded without any I/O operation. * A self-contained and independent function should ‘black box’ receives a predefined I/O desired value. function 1 ( ) { …….. …….. function 2 ( a) .…… ........ } function 2 ( f) { ………… …………. ………… return(e); } Values of argument function result
  • 17. Example : #include <stdio.h> float square(float x); int main( ) { float m,n; printf(“n The number of square:”); scanf(“%f”,&m); n= square(m); printf(“n Square of the given number:%f is %f”,m,n); } float square(float x) { float p; p=x*x; return(p); } Output: The number of square: 4 Square of the given number 4.0000 is 16.0000 3. Function with argument but one return value Argument passing One return value
  • 18. No Argument but Return a value: * A function that any arguments but returns a value to the calling function. * A typical example is the getchar function declared in the header file <stdio.h>. * The getchar function has no parameters but it returns an integer type data that represents a character. int get_number(void); int main( ) { int m=get_number( ); printf(“%d”,m); } int get_number(void) { int number; scanf(“%d”,&number); return(number); } No Argument Return a value
  • 19. Function that return Multiple Value: * A function that return just one value using a return statement. That is because, a return statement can return only one value. * C using the arguments not only to receive information but also to send back information to the calling function. The arguments are used to ‘send out’ information are called output parameters. int math(int x, int y, int *s, int *d); int main( ) { int x=20,y=10,s,d; Math(x,y,&s,&d); printf(“n s=%dn d=%dn”,s,d); } int math(int a,int b,int *sum,int *diff) { *sum=a+b; *diff=a-b; } Output s=30 d=10 Multiple value
  • 20. Nested of function : Nesting of function freely. Main can call function1, which calls function2, which calls function3,………….and so on. float ratio(int x, int y,int z); int difference(int x,int y); main( ) { int a,b,c; scanf(“%d %d %d”,&a,&b,&c); printf(“%fn”,ratio(a,b,c)); } float ratio(int x,int y,int z); { if(difference(y,z)) return(x/(y-z)); else return(0.0); } int difference(int p,int q) { if(p!=q) return(1); else return(0); } main( ) ratio( ) difference( )
  • 21. Recursion : * Recursion is a special case of this process, where a function calls itself. A very simple example of recursion is present in the function. * A called function in turn calls another function a process of ‘chaining’ occurs it used factorial function. Example : main( ) { printf(“n programming in c”); main( ); }
  • 22. Programming in C++ Functions Synopsis : 1. Introduction 2. Main function 3. Function prototyping 4. Call by reference 5. Return by reference 6. Inline function 7. Default arguments 8. Function Overloading
  • 23. Introduction : Dividing a program into functions is one of the major principles of top-down, structured programming. Advantage of using functions is that it is possible to reduce the size of a program by calling and using them at different places in the program. Syntax : int area( ); /* Function declaration */ main( ) { ……. area( ); /* Function call */ } int area( ) /* Function definition */ { …… …… /* Function body */ }
  • 24. Main Function : * C does not specify any return type for the main( ) function which is the starting point for the execution of a program. main( ) { // main program statement; } * The function that have a return value should use the return statement for termination. The main ( ) function in C++ int main ( ) { ……. ( Function should return a value ) …….. return 0; }
  • 25. Function Prototyping : * The prototype describe the function interface to the compiler by giving details such as the number and type of arguments and the type of return values. * A function prototyping a template is always used when declaring and defining a function. * Function prototype is a declaration statement in the calling program Syntax : type function_name (argument-list); Example : float volume(int x,float y,float z);
  • 26. Call by Reference : * A function call passes arguments by value. The called function creates a new set of variables and copies the values of arguments into them. * Call by value method it used to value passes in variables. * The reference variable is a point to address in c++ permits to pass parameters to the function by reference. * The ‘formal’ arguments in the called function become to the ‘actual’ arguments in the calling function. Syntax : swap(a , b); swap(&a,&b); (call-by-value) (call-by-reference)
  • 27. Example : Call By Reference #include<iostream.h> int swap(int *a,int *b); int main( ) { int p=10,q=20; cout<<“n before value p:%d q:%d”; swap(&a,&b); cout<<“n After the value p:%d q:%d”; } int swap(int *a,int *b) { int t; t=*a; *a=*b; *b=t; } Output Before value p:10 q:20 After the value p:10 q:20
  • 28. Return by Reference : * A function also return a reference. For Example : int & max(int &x,int &y) { if(x>y) return x; else return y; } * Since the return type of max( ) is int &, the function returns reference to x or y. * Then a function call such as max(a,b) yield a reference to either a or b depending on their values.
  • 29. Inline Function : * One of the objectives of using function in a program is to save some memory space, which becomes appreciable when a function is likely to be called many times. * To eliminate the cost of calls to small functions, C++ propose a new feature called inline function. * An inline function is a function that is expanded in line when it is invoked. Syntax : Example: inline function-header { function boby } inline double cube (double a) { return(a*a*a); }
  • 30. * It is easy to make a function inline. To prefix the keyword inline to the function definition. All inline functions must be defined before they are called. Example : inline double cube(double a) { return (a*a*a); } Inline expansion may not work are : * For function returning values, if a loop, a switch or a goto exists. * Function not returning values, if a return statement exists. * If function contain static variables. * If inline function are recursive.
  • 31. Example for Inline Function program : #include<iostream.h> using namespace std; inline float mul(float x,float y) { return (x*y); } inline double div(double p,double q) { return(p/q); } int main( ) { float a=12.345,b=9.82; cout<<mul(a,b)<<“n”; cout<<div(a,b)<<“n”; return 0; } Output 121.228 1.25713
  • 32. Default Arguments : * The function assigns a default value to the parameter which does not have a matching argument in the function call. * Default values are specified when the function is declared. Example : float amount(float principal,int period, float rate=0.15); * The default value is specified in a manner syntactically similar to a variable initialization. * The above prototype declares a default value of 0.15 to the arguments rate.
  • 33. * A default argument is checked for type at the time of declaration and evaluated at the time of call. * It provide a default value to a particular argument in the middle of an argument list. int mul(int i.int j=5,int k=10); int mul(int i=5,int j); int mul(int i=0,int j,int k=10); int mul(int i=2,int j=5,int k=10); * Default arguments are useful in situations where some arguments always have the same value.
  • 34. Example : #include<iostream.h> using namespace std; int main( ) { float amount; float value(float p,int n,float r=0.15); void printline(char ch=‘*’,int len=40); printline( ); amount=value(5000.00,5); cout<<“n final value:”; printline(‘=‘); return 0; } float value(float p,int n,float r) { int year=1; float sum=p; while(year<=n) { sum=sum*(1+r); year=year+1; } return (sum); } void printline(char ch,int len) { for(int i=1;i<=len;i++) printf(“%c”,ch); printf(“n”); } Output : ********************** Final value=10056.8 ==================
  • 35. Function Overloading : * A function overloading refers to the use of the same thing for different purposes. * C++ also permits overloading of functions. * This means that we can use the same function name to create functions that performs a variety of different tasks. * This is known as function polymorphism in OOP. Example : /* Declaration */ /* Function calls */ int add(int a,int b); cout<< add(5,10); int add(int a,int b,int c); cout<< add(15,10.0); double add(double x,double y); cout<< add(12.5,7.5); double add(int p,double q); cout<< add(5,10,15); double add(double p,int q); cout<< add(0.75,5);
  • 36. Example : #include<iostream.h> using namespace std; int volume(int); double volume(double ,int ); long volume(long ,int ,int ); int main( ) { cout<<volume(10)<<“n”; cout<<volume(2.5,8)<<“n”; cout<<volume(100L,75,15)<<“n”; return 0; } int volume(int s) { return(s*s*s); } double volume(double r ,int h) output: { return(3.14519*r*r*h); } long volume(long l ,int b,int h) 1000 { return(l*b*h); 157.26 } 112500