Functions in C
Functions in C
Functions in C
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.
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);
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
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;
}
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
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.
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);
}
Storage classes
1. Automatic storage class
2. External storage class
3. Static storage class
4. Register storage class
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.
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.
printf("\n\nEnter Base...:");
scanf("%d",&b);
printf("Enter power...:");
scanf("%d",&p);
String functions:
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
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
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();
}