A function is a self-contained block of statements that is meant to do some specific, well-defined task.
A function is a group of statements that together perform a task.
Function allow a large program to be broken down into a smaller self contained components, each of which
has a definite purpose.
Advantages of using functions
When some specific code is to be used more than once and at different places in the program the use
of functions avoids repetition of that code.
The program becomes easily understandable, modifiable and easy to debug and test.
Every program must have a main function. This main function is used to mark the beginning of the
execution.
int sum(int, int);
int main()
{
int a, b, ans;
printf("Enter two numbers: ");
scanf("%d%d",&a, &b);
ans = sum(a, b); // function call
printf("Sum is %d", ans);
return 0;
}
int sum(int x, int y)
{
int z;
z = x + y;
return z;
}
Some features of above program
The first statement is the declaration of the function which tells the compiler the name of the
function and the data type of the arguments passed. This declaration is also called as prototype.
The declaration of a function is not necessary if the output type is an integer value. In some c
compilers declaratin is not required for all the function.
Funcion call is the way of using the function. A function is declared once, defined once but can be
used a numbber of times in the same program.
When the compiler encounters the function call, the conrol of the program is tranferred to the
function definition the function is then executed line by line and a value is returned at the end.
At the end of the main program is the definition of the function, which can also be called as
process.
The function definiton does not terminate with a semicolon.
A function may or may not return any value. Thus the presence of the
return statement is not necessary. When the return statement is
encountered, the control is immediately passed back to the calling
function.
All functions by default return int. But if the function has to return a
particular type of data the type specifiers can be used along with the
function name.
long int fact(n)
There are two types of functions
Library functions
User-defined functions
Library Functions
C has the facility to provide library functions for performing some operations. These functions are
present in C library and they are predefined.
For example sqrt() is mathematical library function which is used for finding out the square root of
any number.
To use a library function we have to include corresponding header file using the preprocessor
directive #include. For example to use input-output functions like printf(), scanf() we have to
include stdio.h for mathematical library functions we have to include math.h, for string library
functions string.h should be included.
There are total of 15 header files in C. main() is a user
defined function.
#include<stdio.h>
#include<math.h>
int main()
{
double n, s;
printf("Enter a number : ");
scanf("%lf", &n);
s = sqrt(n);
printf("The square root of %.2lf is : %.2lf", n, s);
return 0;
}
/*
This program have three library functions - printf(), scanf() and sqrt()
*/
User-Defined Functions
Users can create their own functions for performing any specific task of the program. These types of
functions are called user-defined functions. To create and use these function, we should know about
these three things-
Function definition
Function declaration
Function call
Reference program ↓
int sum(int, int); // function declaration / prototype
int main()
{
int a, b, ans;
printf("Enter two numbers: ");
scanf("%d%d",&a, &b);
ans = sum(a, b); // function call
// a and b are actual arguments
printf("Sum is %d", ans);
return 0;
}
int sum(int x, int y) // function definition
{
int z;
z = x + y;
return z;
}
Function Declaration
The calling function needs information about the called function.
If definition of the called function is placed before the calling function, then declaration is
not needed.
#include<stdio.h>
int sum(int x, int y) // function definition
{
int s;
s = x + y;
return s;
}
int main()
{
// body
}
Above the definition of sum() is written before main(), so main() knows everything about the
function sum(). But generally the function main() is placed at the top of all, and other
functions are placed after it. In this case, function declaration is needed. The function
declaration is also known as the function prototype, and it informs the compiler about the
following three things -
Name of the function
Number and type of arguments received by the function.
Type of value returned by the function.
Function declaration tells the compiler that a function with these features will be defined and
used later in the program. The general syntax of a function declaration is -
return_type func_name(type1, type2, ...);
Function Definition
The function definition consists of the whole description and code of a function.
It tells what the function is doing and what are its input and outputs.
A function definition consists of two parts - a function header and a function body.
The first line in the function definiton is known as the function header and after this the body
of the function is written enclosed in curly braces.
The return_type denotes the type of the value that will be returned by the function. The
return_type is optional and if not omitted, it is assumed to be int by default.
Function Call
The function definition describes what a function can do, but to actually use it in the program
the function should be called somewhere. A function is called by simply wiriting its name
followed by the argument list inside the parentheses.
func_name(arg1, arg2, ...);
These arguments arg1, arg2, ... are called actual arguments.
Here func_name is known as the called function while the function in which this function called
is placed is known as the calling function.
When a function is called, the control passes to the called function.
If the function returns a value, then this function call can be used like an operand in any
expression anywhere in the program.
s = sum(a, b); /* Assigning the return value of sum() to variable s */
return statement
The return statement is used in a function to return a value to the calling function.
It may also be used for immediate exit from the called function to the calling function without
returning a value.
This statement can appear anywhere inside the body of the function. There are two ways in which
it can be used -
return;
/* Above one is used to terminate the function without returning any value. */
return(expression);
/* Above return statement is used to terminate a function and return a value to the calling funtion. */
Function Arguments
the calling function sends some values to the called function for communication; these values
are called arguments or parameters.
Actual arguments
The arguments which are mentioned in the function call are known as actual arguments, since
these are the values which are actually sent to the called function.
Actual arguments can be written in the form of variables, constants or expressions or any
function call that returns a value.
func(x)
func(a*b, c*d+b)
func(1, 2, sum(a, b))
Formal arguments
The name of the arguments, which are mentioned in the function definition are called formal
arguments since they are used just to hold the values that are sent by the calling function.
These formal arguments are simply like other local variables of the function which are
created when the function call starts and are destroyed when the function ends. However
there are two differences.
First is that formal arguments are declared inside parentheses while other local
variables are declared at the beginning of the function block.
The second difference is that formal arguments are automatically initialzed with the
values of the actual arguments passed, while other local variables are assigned
values through the statements written inside the function definition.
The order, number and type of actual arguments in the function call should match with the
order, number and type of formal arguments in the function definition.
Types of Functions on the basis of the arguments and return value
Functions with no arguments and no return value.
Functions with no arguments and a return value.
Functions with arguments and no return value.
Functions with arguments and a return value.
Functions with no arguments and no return value
Functions that have no arguments and no return value are written as ↓
These types of functions do not receive any arguments but they can return a value.
int func(void);
main()
{
int r;
.....
r = func();
.....
}
int func(void)
{
......
......
return (expression);
}
Function with arguments but no return value
These types of functions have arguments hence the calling function can send data to the called
function but the called function does not return any value.
These types of functions have arguments, so the calling function can send data to the called
function, it can also return any value to the calling function using return statement.
int func(int, int);
main()
{
int r;
......
r = func(a, b);
.....
func(c, d);
}
int func(int a, int b)
{
......
......
return (expression);
}
Local, Global and Static Variables
Local Variables
The variables that are defined within the body of a function or a block, are local to that
function block only and are called local variables.
func()
{
int a, b;
.....
.....
}
Here a and b are local variables which are defined within the body of the function func().
Local variables can be used only in those functions or blocks, in which they are declared.
The same variable may be used in different functions. For example ↓
func1()
{
int a=2, b=4;
......
......
}
func2()
{
int a = 15, b = 20;
.....
.....
}
Here values of a = 2 and b = 4 are local to the function func1() and a = 15 and b = 20 are local
to the function func2().
Global Variables
The variables that are defined outside any function are called global variables.
All function in the program can access and modify global variables.
It is used to declare a variable global if it is to be used by many functions in the program.
Global variables are automatically initialized to 0 at the time of declaration.
Program to understand the use of global variables ↓
#include<stdio.h>
int a, b = 6;
main()
{
printf("Inside main() : a = %d, b = %d\n", a, b);
func1();
func2();
}
void func1(void)
{
printf("Inside func1() : a = %d, b = %d\n", a, b);
}
void func2(void)
{
int a = 8;
printf("Inside func2() : a = %d, b = %d\n", a, b);
}
OUTPUT ↓
Inside main() : a = 0, b = 6
Inside func1() : a = 0, b = 6
Inside func2() : a = 8, b = 6
Here a and b are declared outside all functions hence they are global variables.
The variable a will be initialized to 0 automatically since it is a global variable.
Now we can use these variables in any function.
In func2(), there is a local variable with the same name as global variable. Whenever there is a
conflict between a local and global variable, the local variable gets the precedence.
So inside func2() the value of local variable gets printed.
Static Variables
Static variables are declared by writing keyword static in front of the declaration.
static type var_name;
A static variable is initialized only once and the value of a static variable is retained
between function calls. If a static variable is not initialized then it is automatically
initialized to 0.
Program to understand the use of static variables ↓
#include<stdio.h>
main()
{
func();
func();
func();
}
void func(void)
{
int a = 10;
static int b = 10;
printf("a = %d b = %d\n", a, b);
a++;
b++;
}
a = 10 b = 10
a = 10 b = 11
a = 10 b = 12
Here 'b' is a static variable. First time when the function is called 'b' is initialized to 10.
Inside the same function the value of 'b' becomes 11. This value is retained and when next time
the function is called value of 'b' is 11 and the initializaion is neglected.
Similarly when third time function is called, value of 'b' is 12. Note that the variable 'a',
which is not static is initialized on each call and its value is not retained.
Recursion
Recursion is a powerful technique of writing a complicated algorithm in an easy way.
According to this technique a problem is defined in terms of itself.
The problem is solved by dividing in into smaller problems, which are similar in nature to the
original problem.
To implement recursion technique in programming, a function should be capable of calling itself,
this facility is available in C.
The function that calls itself (inside fuction body) again and again is known as a recursive
function.
In recursion the calling function and the called fucntion are same.
There should be a terminating condition to stop a recursive function, otherwise it will keep on
calling itself infinitely and will never return.
Before writing a recursive function for a problem we should consider these points-
We should be able to define the solution of the problem in terms of similar type of smaller
problem. At each step we get closer to the final solution of our original problem.
There should be a terminating condition to stop recursion.
Passing arrays to functions
#include <stdio.h>
float avg(int arr[], int s);
int main()
{
int arr[6] = {1, 2, 3, 4, 5, 6};
printf("The average is : %.2f", avg(arr, sizeof(arr) / sizeof(int)));
return 0;
}
float avg(int arr[], int s)
{
float avg;
int sum = 0, i;
for (i = 0; i < s; i++)
{
sum += arr[i];
}
return (float)sum / s;
}
#include <stdio.h>
int max(int arr[], int s);
int min(int arr[], int s);
int main()
{
int arr[6] = {1, 2, 3, 4, 5, 6};
printf("The Maximum number is : %d\n", max(arr, sizeof(arr) / sizeof(int)));
printf("The Minimum number is : %d\n", min(arr, sizeof(arr) / sizeof(int)));
return 0;
}
int max(int arr[], int s)
{
int i, max = arr[0];
for (i = 1; i < s; i++)
{
if (arr[i] > max)
max = arr[i];
}
return max;
}
int min(int arr[], int s)
{
int i, min = arr[0];
for (i = 1; i < s; i++)
{
if (arr[i] < min)
min = arr[i];
}
return min;
}
Passing strings to functions
#include <stdio.h>
void printit(char words[])
{
printf("The words are : %s", words);
}
int main()
{
char words[20] = "hehe";
printit(words);
return 0;
}
Pre-processor
The pre-processor is a program which process the source code before it passes through compiler.
Pre-processor are placed in source program before the main line, it begins with symbol '#' and do
not require a semicolon at the end.
The commonly use pre-processor directives are -
#define
#undef
#include
#ifdef
#endif
#if
#else
The pre-processor directives are divided into three categories -
Macro substitution directive
File inclusion directive
Compiler control directive
Macro Substitution directive
#define MAX 500
#define sqrt(x) x*x // macro with arguments