Sei sulla pagina 1di 17

FUNCTIONS

DEFINE FUNCTION:
A function is a self-contained block of code which is used to perform particular task.
(Or)
A function is a group of related statements which is used to perform particular task
according to the user request.

Types of Functions:
Functions are classified into two categories
1. Library functions/Predefined functions.
2. User defined functions.
1. Library functions/Predefined functions:
The functions which are provided by the system (or) compiler are called as library functions.
Example:
printf(), scanf(), getch(), getchar(), getche(), etc…
2. User defined functions:
The functions which are developed by the users to perform particular task are called as user-
defined functions.
Example:
add(), mul(), div(), average(), etc…

Note: The main difference between library functions and user defined functions is that library
functions are not required to be written by user whereas a user-defined function has to be
developed by the user at the time of writing a program.

NEED FOR USER-DEFINED FUNCTIONS:

 If the program is too large and complex then the task of debugging, testing and maintaining
becomes very difficult.
 If the program is divided into functional parts, then each part may be independently coded
and later combined into a single unit.
 If the program is divided into sub parts (or) functions then it is very easy to debug, test and
maintain the program.

ADVANTAGES OF FUNCTIONS:
The following are the advantages of user-defined functions
1. By using functions we can avoid rewriting of the same code again and again.
2. It is very easy to write a function that does a particular job
3. It facilitates top-down modular programming
4. The length of the source program can be reduced by using functions
5. Saving memory space
6. Efficient, clear and compact source code
7. Easier to write, testing and debugging individual functions
8. A function may be used by many other programs.
There are 3 points to be remembered while working with functions.
 Function Declaration
 Function call
 Function Definition
Function declaration:
The declaration describes function name, no. of arguments, type of argument and a return
value. This feature is also called function prototype.
Syntax:-
< return type > function name (arg list);
ex:-
int add(int,int);

return fun..name data type of


type the arguments

Note: If the function is not returning any value or it is not accepting any arguments then it is
specified with the keyword void.
Ex:
Void message (void);

Function call:
It means calling the function. The arguments passed at function invocation are known as actual
arguments.
Syntax:-
<variable name> = function name( arg1,arg2,. . . );
ex:-
c=add(a,b);
Actual arguments
The returning value of add() is assigned to variable C.
Function definition:
It means defining the user defined function.
Syntax:-
< return type > functions name(arg1,arg2,. . .)
{
------
------
}
ex:-
int add(int x,int y)
{
int z; Formal arguments
z=x+y;
return(z);
}
Copy of the variables a, b is taken in x and y
z is the local variable used within the function.
The returning value is returned with return statement

Program flow:
When a function is called the flow of execution of main program is halted and the control
passes to the function along with the values of actual arguments. The actual arguments are copied
to formal arguments, statements within the function (UDF) are executed and the return statement
takes back the control to the main function along with a value (if any).

main()
f1()
{
{…..
……..
……
……..
}
f1();
Actual arguments:
……. from the calling function to call() are called actual arguments. The
The arguments that are passed
actual arguments can be constants.
Ex:- c=add(a,b); }
c=add(10,20);
Formal arguments:
The arguments that are received in the function definition are known as formal arguments.
In the above example x and y are formal arguments.
Note:-
The data type, order of appearance and the no of actual arguments must be same as those of formal
arguments

THE ELEMENTS OF FUNCTION:


Every function in the C language includes the following elements.
1. Return type
2. Function name
3. list of parameters/arguments
4. Local variable declarations
5. Function statements
6. Return value
All the six elements are grouped into two parts
 Function header (Return type, function name, list of parameters)
 Function body (local variables, statements and return value)

The general form of a function definition is given bellow


return_type function_name(arg1,arg2,ect…)

local variable declaration;

statement1;

statement2;

…………

…………

return (expression)

}
Example1: Example2:
int add(int a,int b) void message()
{ {
int sum=a+b; printf(“hiiiiii”);
return sum; }
}
RETURN VALUES AND THEIR TYPES:
A function may or may not send back any value to the calling function. By using return
statement we can send back the data from the called function to calling function.
The syntax of the return statement is given bellow
Syntax:
return;
return(expression)
Example:
int sum(int a,int b)
{
int sum;
sum=a+b;
return (sum); (or) return sum;
}

DEFINE A FUNCTION CALL:


Function call:
A function can be called by simply using the function name followed by a list of arguments
enclosed in parentheses and separated by commas.
If the function does not require any arguments, an empty pair of parentheses must follow
the function’s name.
A function gets called when the function name is followed by a semicolon.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
message(); // invoking (or) calling a function
getch();
}
message() // called function
{
printf(“good morning”);
}
When we call any function from main() function, the control will goes to the called function
and it will execute the code within that function and return the result to the calling function.
A function can be called any number of times. Any function can be called from any other
function. Even main () can be called from other functions.

Note: We have seen that the main function is not invoked/called anywhere in the program. This is
because the operating system automatically calls the main function upon execution of the program.
For this reason, there must always be a main function present; otherwise; the program cannot run.

FUNCTION PROTOTYPE/DECLARATION:
All functions in C program must be declared, before they are called/invoked. A function
declaration/prototype consists of four parts.
1. Return type
2. Function name
3. Parameters/Arguments list
4. Terminating semicolon

The syntax of function prototype is given bellow


Syntax:
return_type function_name(parameter list);
Example:
int add(int a, int b);
void message();

FUNCTION CATEGORIES:

A function, depending on whether arguments are present or not and whether a value is
returned or not, may belongs to one of the following categories.

1. Functions with no arguments and no return values.


2. Functions with arguments and no return values.
3. Functions with no arguments and return values.
4. Function with arguments and return values.

1. Functions with no arguments and no return values:


These are the functions in which no parameters are passed from the calling function to
called function and no values returned from the called function to calling function.
Example program:
#include<stdio.h>
#include<conio.h>
void main()
{
sum();
getch();
}
void sum() /* no arguments*/
{
int a=10,b=20;
int sum;
sum=a+b;
printf(“the sum is: %d”,sum);
} /* no return statement */

2. Functions with arguments and no return values:


These are the functions in which arguments are passed from the calling function to the
called function but no values are returned from the called function to calling function.
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
sum(a,b);
getch();
}
void sum(int x,int y) /*it has arguments*/
{
int result;
result=x+y;
printf(“the sum is: %d”,result);
} /* no return statement */
3. Functions with no arguments and return values
In this category of function no arguments are passed from calling function to the called
function but values are returned from called function to the calling function.
Example program:
#include<stdio.h>
#include<conio.h>
void main()
{
int result;
result=sum( );
printf(“the sum is:%d”,result);
getch( );
}
void sum( ) /*it has no arguments*/
{
int a=10,b=20;
int sum;
sum=a+b;
return (sum);
} /* return statement */

4. Function with arguments and return values


These are the functions in which parameters are passed from calling function to the called
function and values are returned from called function to the calling function.
Example program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=5;
int result;
result=sum(a,b);
printf(“the sum is:%d”,result);
getch();
}
void sum(int x, int y ) /*it has arguments*/
{
int sum;
sum=x+y;
return (sum);
} /* return statement */
PARAMETER PASSING TECHNIQUES

During thefunction call the actual parameters are passed in two ways two ways:
 Call by value
 Call by reference
Call by value:
Call by value means calling the function by passing the values to it.

Ex:
# include <stdio.h>
void swap(int,int);
void main()
{
int a,b;
clrscr();
printf("Enter value for A:");
scanf("%d",&a);
printf("Enter value for B:");
scanf("%d",&b);
swap(a,b);
getch();
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("\nThe value of A:%d",x);
printf("\nThe value of B:%d",y);

}
Note:
Values of A and B variables are copied in X and Y, so the changes in X and Y will not reflect to the
variables A and B.
Call by reference:
Calling the function by passing reference (address) is known as call by reference.
Program to find biggest of two no’s using functions:
# include <stdio.h>
int big(int *,int *);
main()
{
int a,b,biggest;
clrscr();
printf("Enter two nos..:");
scanf("%d%d",&a,&b);
biggest=big(&a,&b);
printf("Biggest no is:%d",biggest);
getch();
}
int big(int *x,int *y)
{
if(*x>*y)
return(*x);
else
return(*y);
}

RECURSIVE FUNCTIONS:
A function called by itself is called as recursion.
Recursion is the process or technique by which a function calls itself. A recursive function
contains a statement within its body, which calls the same function. Thus, it is also called as circular
definition. A recursion can be classified as direct recursion and indirect recursion. In direct recursion,
the function calls itself and in the indirect recursion, a function (f1) calls another function (f2), and
the called function (f2) calls the calling function (f1).

Example program1:
#include<stdio.h>
#include<conio.h>
void main()
{
printf(“this is recursion program’);
main();
}
Example program2:
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int n,factorial;
clrscr();
printf(“\n enter any number to find factorial:”);
scanf(“%d”,&n);
factorial=fact(n);
printf(“factorial of %d is :%d”,n,factorial);
getch();
}
int fact(int n)
{
int result;
if(n==1)
{
return 1;
}
else
{
result=n*fact(n-1);
return result;
}
}
PASSING ARRAYS TO FUNCTIONS
Like the values of simple variables, it is also possible to pass the values of an array to a
function. To pass a one dimensional an array to a calling function, it is sufficient to list the name of
the array, without any subscripts, and the size of the array as arguments.

To pass a one dimensional an array to a called function, it is sufficient to list the name of the
array, with subscripts, and the size of the array as arguments.
Example program
#include<stdio.h>
#include<conio.h>
float largest(float a[],int n);
void main()
{
float large;
float value[4]={2.5,-4.75,1.2,3.67};
large=largest(value,4);
printf(“the largest value is%f\n”,large);
}
float largest(float a[],int n)
{
int i;
float max;
max=a[0];
for(i=1;i<n;i++)
{
if(max<a[i])
{
max=a[i];
}
}
return (max);
}

SCOPE AND LIFE TIME OF A VARIABLE IN FUNCTIONS


Scope:
The Scope of variable determines over what region of the program a variable is actually available for
use (active).
Lifetime:
The lifetime of a variable refers to the period of time, which starts on entering into the method for
execution and ends with the method termination i.e., it is the time interval over which a variable
exists during the method execution.

Storage classes
1. Automatic storage class
2. External storage class
3. Static storage class
4. Register storage class

1. Automatic storage class


Automatic variables are declared inside a function in which they are to be utilized. They are created
when the function is called and destroyed automatically when the function is exited. Hence the
name automatic. Automatic variables are therefore private or local to function in which they are
declared.
Syntax: auto int a;
Variable location : Variable is stored in memory.
Default initial value : Garbage value.
Variable scope : Local to the block in which variable is defined.
Variable lifetime : Variable is active till the control is present in the block in
Which variable is defined.
2. External storage class
Extern is used to give a reference of global variables that is visible to all the program flies.
When you use ‘extern’ the variable can’t be initialized as all it does is point the variable name at a
storage location that has been previously defined.
When you have multiple files and you define a global variables or function which will be
used in other flies to give reference of defined variables or function.
Syntax: extern int a;
Variable location : variable is stored in memory.
Default initial value : the default value is assigned to variable is zero.
Variable scope : global
Variable lifetime : variable is active till the control is present in the block in which
Variable is defined.
3. Static storage class:
As the name suggests the value of static variables persists until the end of the program. A
variable can be declared static using the keyword static like
Syntax: static int x;
Variable location : variable is stored in memory.
Default initial value : default value assigned to variable is zero.
Variable scope : local to the block in which variable is defined.
Variable lifetime : variable is active between different function calls.

4. Register storage class:


We can tell the complier that a variable should be kept in one of the machine’s registers
instead of keeping in the memory. Since a register access is much faster than a memory access.
Syntax: register int count;
Variable location : variable is stored in cpu registers. .
Default initial value : garbage value.
Variable scope : local to the block in which variable is defined.
Variable lifetime : variable is active till the control is present in the block in which
Variable is defined

GLOBAL VARIABLES:
The variables which are declared outside any function are called global variables. These
variables can be accessed by all the functions in the program. Default value for global variable is
zero.

Passing the global variables as parameters using sample programs


#include<stdio.h>
#include<conio.h>
#define pi 3.141
float area; /* global variable*/
void main()
{
int radius;
printf(“enter radius value”);
scanf(“%d”,&radius);
calculate_area();
printf(“the area is %f”,area);
getch();
}
calculate_area()
{
area=pi*radius*radius;
}

LOCAL VARIABLES:
The variables which are declared within any function are called local variables. These
variables can be accessed only by the function in which they are declared. Default value for local
variable is a garbage value.

EXTERNAL VARIABLES:
Extern variables are used to give a reference of global variables that is visible to all the
program flies. When you use ‘extern variables’ can’t be initialized as all it does is point the variable
name at a storage location that has been previously defined.
When you have multiple files and you define a global variables or function which will be
used in other flies to give reference of defined variables or functions.

DIFFERENCE BETWEEN LOCAL AND EXTERNAL VARIABLE

Local Variables Global Variable


Variables declared within the functions are Variables declared outside all functions are
called local variables called global variables
These are known only in the function in which Global variables in C are declared at the
they are declared beginning of a program before the main()
function
These are not known to other functions These may be accessed by any function
The local variables in one function have no Global variables provides two-way
relationship to the local variables in another communication among functions
function

WORKING WITH LIBRARY FUNCTIONS:


 Numeric functions:

abs() – Returns absolute value of an integer


sqrt() – Finds square root
pow() – calculates a value raised to a power.
And many more….
# include <stdio.h>
# include <math.h>
main()
{
int no,b,p;
printf("Enter a no..:");
scanf("%d",&no);
printf("Square root of %d is %lf..",no,sqrt(no));

printf("\n\nEnter Base...:");
scanf("%d",&b);
printf("Enter power...:");
scanf("%d",&p);

printf("%d power %d is %lf..",b,p,pow(b,p));


getch();
}

 String functions:

strlen() – Finds length of the string


strrev() – Reverses a string
strcmp() – compares two strings
strcpy() – copies one string to another string
strupr() – converts a string to uppercase
strlwr() – converts a string to lowercase
And many more…..
# include <stdio.h>
# include <string.h>
main()
{
char str[20];
clrscr();
printf("Enter a string....");
scanf("%s",&str);
printf("\nLength of the string is..:%d",strlen(str));
printf("\nString in uppercase...:%s",strupr(str));
printf("\nString in lowercase..:%s",strlwr(str));
printf("\nString in reverse..:%s",strrev(str));
getch();
}
Pre-processor Directives:

 Before a C program is compiled in a compiler, source code is processed by a program


called pre-processor. This process is called pre-processing.
 Commands used in pre-processor are called pre-processor directives and they begin
with “#” symbol.

Below is the list of pre-processor directives that C programming language offers.

Preprocessor Syntax/Description
Syntax: #define macro value
This macro defines constant value and can be any of the basic data
Macro Substitution
types.
Ex: #define pi 3.14
Syntax: #include <file_name>
Header file The source code of the file “file_name” is included in the main program
inclusion at the specified place.
Ex: #include<stdio.h>
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program before
compilation
compilation with respect to the condition.
#include <stdio.h>
#define X 100
void main()
{
#ifdef X
printf("X is defined \n");
#else
printf("X is not defined\n");
#endif
getch();
}

Basics of Pointers
Pointers:
Pointers are the special variables which are used to store the addresses of other variables.
The two operators used in pointers are:
& - Address of operator
* - value at/de-referencing/indirection operator
Ex:-
int no=10;
The above declaration tells C compiler to:
Reserve space in memory to hold the integer value.
Assign the name no to the memory location.
Store the value 10 in that location

Location name
no
10 Value at the location

10
65460 Location addresses

Write a program to Demonstrate pointers:


#include <stdio.h>
void main()
{
int no=10;
int *p;
clrscr();
p=&no;
printf("Value of no is:%d",no);
printf("\nAddress of no is:%u",&no);
printf("\nValue of p is:%u",p);
printf("\nValue at the address of p is:%d",*p);
getch();
}
Call by reference:
Call by reference means calling the function by passing the addressed to it.
# include <stdio.h>
void swap(int *,int *);
void main()
{
int a,b;
clrscr();
printf("Enter value for A:");
scanf("%d",&a);
printf("Enter value for B:");
scanf("%d",&b);
swap(&a,&b);
printf("\nThe value of A:%d",a);
printf("\nThe value of B:%d",b);
getch();
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
return;
}
Note:
Address(reference) of A and B variables are taken in X and Y, so the changes in X and Y will reflect to
the variables A and B.

Programs:
# include <stdio.h>
void main()
{
int a,b,c;
int *p1,*p2;
clrscr();
printf("Enter two nos:");
scanf("%d%d",&a,&b);
p1=&a;
p2=&b;
c=*p1+*p2;
printf("Result is:%d",c);
getch();
}
Passing array address to a function.
# include <stdio.h>
int i; /* global declaration */
main()
{
void disp(int *);
int arr[10];
clrscr();
for(i=0;i<10;i++)
{
printf("Enter a no:");
scanf("%d",&arr[i]);
}
disp(&arr[0]); /* disp(arr) */
getch();
}
void disp(int *x)
{
for(i=0;i<10;i++)
{
printf("\nElement at %u is %d..",x+i,*(x+i));
}
}
Passing character array address to a function
# include <stdio.h>
main()
{
void dispname(char *);
char name[20];
clrscr();
printf("Enter ur name..:");
scanf("%s",&name);
dispname(name);
getch();
}
void dispname(char *x)
{
while(*x!='\0')
{
printf("\nChar at %u is %c... ",x,*x);
x++; /* increments to next address */
}
}
*** Pointer variable of any data type will occupy 2 bytes of space in the main memory.
Ex:-
int no=10,*p1;
float x=12.25,*p2;
char ch=’a’,*p3;
p1=&no; p2=&x; p3=&ch;
Memory representation

P1 P2 P3

65460 540 546

no x ch

10 12.25 a
65460 65461 540 541 542 543 546

Though pointer variable of any data type occupies 2 bytes of memory, all the pointer
variable cannot be declared as int type. Because while accessing data usingpointer variables, its
incrimenation depends upon its data type.
Use of pointers:
Dynamic memory allocation is possible.
Passing array to functions.
Call by reference ( To change the value actual variable ).
Pointer notation is faster than array notation.
To return more than one value from a function.
Pointers are power of C.
The secret of C is its use of pointers.
More about scanf():
main()
{
int no;
char str[20];
clrscr();
printf("Enter a no..:");
scanf("%d",&no); /* call by address */
printf("Enter a string...:");
scanf("%s",str); /* call by address */
printf("%d - %s",no,str);
getch();
}
Explanation:
To change the value of a variable address is passedso & is used.
But strings are character arrays, where the variable will contain base address, so & is not required
while working with strings.

sizeof keyword:
It is used to get the size of a variable or data type
i.e number of bytes allocated.
# include <stdio.h>
main()
{
int x;
char y;
float z;
clrscr();
printf(“Size of x is:%d”,sizeof(x));
printf(“Size of int is:%d”,sizeof(int));
printf(“Size of y is:%d”,sizeof(y));
printf(“Size of char is:%d”,sizeof(char));
printf(“Size of z is:%d”,sizeof(x\x));
printf(“Size of float is:%d”,sizeof(float));
getch();
}
const keyword:
If the value of a variable is fixed and should not be changed even accidentally, then such a
variables is defined as const.
# include <stdio.h>
main()
{
const float PI=3.14;
clrscr();
printf(“%f”,PI);
getch();
}

Potrebbero piacerti anche