Unit V Functions
Unit V Functions
Functions
10 Hours
14 Marks
Industry identified competency addressed by this course:
- Develop C programs to solve broad-based computer related problems.
5.1.2Definition of Function
Function is a self-contained block of statements that performs a specific
task.
Library functions are already defined functions and they can be directly
used by a programmer by just including the header file in which they are
defined. We have already used printf( ) and scanf( ) library functions for using
which we have included the header file stdio.h.
User-defined functions need to be defined by a programmer as per his/her
requirements. These functions can be used by the same programmer or other
programmers afterwards.
2 of 20
5.1.5 Prototype of Function
Argument is nothing but a value or reference passed to a function. We
can pass any number of arguments (0 or more) to a function. They are also called
as parameters.
Also, function may return a value (maximum one value can be returned by
a function). Return-type of a function is data type of value which function is
returning. If a function does not return any value, its return-type is considered to
be „void‟.
Every function is uniquely identified by its prototype. Prototype of a
function is nothing but combination of return-type, name of function (i.e.
identifier used for function), number of arguments and types of arguments.
Prototype of a function is used for uniquely identifying a function. Syntax of a
prototype is given below.
return-type function-name(datatype-of-arg1,datatype-of-arg2,…)
Examples:
1.
int add(int,int)
Function named „add‟ takes two arguments both of type
integer and returns an integer value.
2.
void display_division(float,float)
Function named „display_division‟ takes two arguments both
of type float and does not return any value.
3.
void disp( )
Function named „disp‟ does not take any arguments and does
not return any value.
4.
int get_val( )
Function named „get_val‟ does not take any arguments and
returns an integer value.
abs( ) function:
This function returns absolute value of passed parameter. Prototype of
this function is given below.
3 of 20
int abs(int)
This function expects an integer parameter and returns an integer value.
Example:
int a= – 5634;
int b=831;
printf(“\nAbsolute value of %d is %d”,a,abs(a));
printf(“\nAbsolute value of %d is %d”,b,abs(b));
Output:
ceil( ) function:
This function returns nearest higher integer (i.e. ceiling value) of passed
floating-point parameter. Prototype of this function is given below.
double ceil(double)
This function expects a floating-point parameter and returns an integer
value (integer found as double).
Example:
doublex = 6.346;
doubley = 5.754;
printf(“\nCeiling value of %lf is %d”,a,ceil(a));
printf(“\nCeiling value of %lf is %d”,b,ceil(b));
Output:
floor( ) function:
This function returns nearest lower integer (i.e. floor value) of passed
floating-point parameter. Prototype of this function is given below.
double floor(double)
This function expects a floating-point parameter and returns an integer
value (integer found as double).
Example:
double x = 6.346;
double y = 5.754;
printf(“\nFloor value of %lf is %d”,a,floor(a));
printf(“\nFloor value of %lf is %d”,b,floor(b));
Output:
4 of 20
sin( ), cos( ), tan( ) functions:
These functions return sine, cosine and tangent of passed floating-point
parameter (in radians). Prototypes of these functionsare given below.
double sin(double)
double cos(double)
double tan(double)
Example:
/*M_PI is a predefined constant defined in math.h for value of pi. */
printf(“\nsin(30)= %lf”,sin(M_PI/6)); /*πC=1800 */
printf(“\ncos(60) = %lf”,cos(M_PI/3));
printf(“\ntan(45) = %lf”,tan(M_PI/4));
Output:
sin(30) = 0.5
cos(60) = 0.5
tan(45) = 1.0
pow( ) function:
This function returns first parameter raised to the power second
parameter. Prototype of this function is given below.
double pow(double,double)
This function expects two floating-point parameters and returns an
floating-point value.
Example:
double x = 3;
double y = 4;
printf(“\n%lf raised to power %lf = %lf”,x,y,pow(x,y));
Output:
sqrt( ) function:
This function returns square root of its argument. Prototype of this
function is given below.
double sqrt(double)
This function expects floating-point parameter and returns an floating-
point value.
Example:
double x = 256;
printf(“\nSquare root of %lf is %lf”,x.sqrt(x));
5 of 20
Output:
strlen( ) function:
This function returns length of string(i.e. number of characters in the
string) passed as parameter. Prototype of this function is given below.
int strlen(char *)
This function expects a string parameter and returns an integer value.
Example:
char name[ ]=“SainaNehwal”;
printf(“Length of the string is %d”,strlen(name));
Output:
Length of the string is 12
strcpy( ) function:
As string is not a basic data type in C, we cannot directly assign a string to
another character array using „=‟ operator. The function strcpy( ) is used for
string-assignment. Prototype of this function is given below.
void strcpy(char *destination, char *source)
This function takes two parameters. Contents of source string (second
parameter) get assigned to destination string (first parameter).
Example:
char name[ ]=“ViratKohli”;
charcaptain[20];
strcpy(captain,name);
printf(“Original string is %s”,name);
printf(“\nCopied string is %s”,captain);
Output:
Original string is ViratKohli
Copied string is ViratKohli
strcat( ) function:
This function is used for concatenation or joining of two strings. (As string
is not a basic data type in C, we cannot use directly „+‟ operator for
concatenation).Prototype of this function is given below.
void strcat(char *destination, char *source)
Here, destination and source are character arrays. When this function is
executed, source string (second parameter) is appended to destination string
(first parameter) while source string remains as it is.
6 of 20
Example:
charstr1[20]=“Table”;
charstr2[10]=“Tennis”;
strcat(str1,str2);
printf(“str1 is %s”,str1);
printf(“\nstr2 is %s”,str2);
Output:
str1 is TableTennis
str2 is Tennis
strcmp( ) function:
As string is not a basic data type in C, we cannot directly compare two
strings using relational operators. The function strcmp( ) is used for comparing
two strings. It does alphanumeric comparison based on ASCII values of the
characters. (Every character has unique ASCII code i.e. American Standard Code
for Information Interchange). Prototype of this function is given below.
int strcmp(char *string1, char *string2)
This function accepts two parameters as strings and returns an integer
value. Meaning of value returned by this function is discussed in table below.
Return Value Meaning
0 If both the parameter strings are equal (i.e. string1=string2)
<0 If first string is lesser than second string (i.e. string1<string2)
>0 If first string is greater than second string (i.e. string1>string2)
Example:
char str1[ ]=“Vinit”;
char str2[ ]=“Vineet”;
int result;
result=strcmp(str1,str2);
if(result==0)
printf(“Strings are equal”);
if(result<0)
printf(“First string is alphabetically lesser than second string”);
if(result>0)
printf(“First string is alphabetically greater than second string”);
Output:
First string is alphabetically greater than second string
isalnum( ) function:
7 of 20
This function returns non-zero value if the character passed as parameter
is alphabet („a‟ to „z‟ or „A‟ to „Z‟) or digit („0‟ to „9‟). Prototype of this function is
given below.
int isalnum(char)
This function expects a character parameter and returns an integer value.
isalpha( ) function:
This function returns non-zero value if the character passed as parameter
is an alphabet („a‟ to „z‟ or „A‟ to „Z‟). Prototype of this function is given below.
int isalpha(char)
This function expects a character parameter and returns an integer value.
isdigit( ) function:
This function returns non-zero value if the character passed as parameter
is a digit („0‟ to „9‟). Prototype of this function is given below.
int isdigit(char)
This function expects a character parameter and returns an integer value.
islower( ) function:
This function returns non-zero value if the character passed as parameter
is lowercase alphabet („a‟ to „z‟). Prototype of this function is given below.
int islower(char)
This function expects a character parameter and returns an integer value.
isupper( ) function:
This function returns non-zero value if the character passed as parameter
is uppercase alphabet („A‟ to „Z‟). Prototype of this function is given below.
int isupper(char)
This function expects a character parameter and returns an integer value.
atoi( ) function:
This function returns integer value of the string passed as parameter.
Prototype of this function is given below.
int atoi(char)
This function expects a character parameter and returns an integer value.
Example:
char str[ ] = “27”;
printf(“Integer value of the string %s is %d”, str, atoi(str));
Output:
Integer value of the string 27 is 27
atof( ) function:
This function returns floating-point value of the string passed as
parameter. Prototype of this function is given below.
double atoi(char)
This function expects a character parameter and returns a double value.
8 of 20
Example:
char str[ ] = “589.432”;
printf(“Floating-point value of the string %s is %d”, str, atof(str));
Output:
Integer value of the string 589.432 is 589.432
Before calling (or defining) a function its prototype must be declared. This
is called function declaration.
Function definition is part of the program where a block of statements
that must be carried out in a function are defined. Function body is nothing
but the block of statements in a function definition.
When a function defined by programmer is to be executed, it should be
called. Function call is a statement used for executing a function. This contains
name of function along with its actual arguments.
Example:
main( )
{
int area_of_rectangle(int,int); /* Function declaration */
int length,breadth,area;
Example:
main( )
{
int length,breadth,area;
void function-name( )
Example:
void display( )
{
10 of 20
printf(“Welcome to Modular Programming\n”);
return;
}
Example:
void product(int a, int b)
{
int result;
result = a * b ;
printf(“Product of %d and %d is %d\n”,a,b,result);
return;
}
return-type function-name( )
Example:
int getValidAge( )
{
int age;
do
{
printf(“Enter valid age (above 16): ”);
scanf(“%d”,&age);
}while(age<16);
return age; /* Or return(age); */
}
Example:
float area_of_circle(int radius)
{
11 of 20
float a;
a = 3.14 * radius * radius;
return a; /* Or return(a); */
}
12 of 20
5.3.4.2 Register Storage Class
Variable of this storage class are stored in CPU registers due to
which fastest access of such variables is possible.
Their default initial value is a random or a garbage value.
These variables are local to the block where they are declared.
They retain their values only within the block where they are
declared.
We have to use keyword „register‟ for declaring register variables.
e.g.
void fun2( )
{
register int c;
}
main( )
{
fun3( );
fun3( );
fun3( );
fun3( );
}
Output:
0
1
2
3
13 of 20
Here variable „a‟ has static storage class. Therefore it retains its
value in different function calls. As the default value of such
variable is zero, the output above is starting from zero.
Example 1:
/* program for product of two numbers */
main( )
{
int result,no1,no2; /* variables result, no1 and no2 are local to main( ) */
int product(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&no1,&no2);
result=product(no1,no2); /* here values of no1 and no2 are passed */
printf(“Product of %d and %d is %d\n”,no1,no2,result);
}
14 of 20
/* value of no1 gets copied to x and value of no2 gets copied to y */
int product(int x, int y) /* variables x and y are local to product( ) function */
{
int z; /* variable z is local to product( ) function */
z = x * y;
return(z);
}
Example 2:
/* program for product of two numbers */
main( )
{
int result,no1,no2; /* variables result, no1 and no2 are local to main( ) */
int product(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&no1,&no2);
result=product(no1,no2); /* here values of no1 and no2 are passed */
printf(“Product of %d and %d is %d\n”,no1,no2,result);
}
/* value of no1 gets copied to no1 of function product( ) and value of no2 gets
copied to no2 of function product( ). Here even if the names of variables are same,
no1 and no2 variables of main( ) function and no1 and no2 variables of product( )
function are different */
int product(int no1, int no2) /* no1 and no2 are local to product( ) function */
{
int z; /* variable z is local to product( ) function */
z = no1 * no2;
return(z);
}
Example 1:
/* program for swapping of two variables (call by value) */
main( )
{
int x,y;
void swap(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping: x = %d, y = %d\n”,x,y);
swap(x,y); /* here values of x and y are passed */
15 of 20
printf(“After swapping: x = %d, y = %d\n”,x,y);
}
Output:
Please enter two numbers: 24 76
Before swapping: x = 24, y = 76
After swapping: x = 24, y = 76
main( )
{
---
function-name(&p1[,&p2,…]); /* Function Call */
---
}
Syntax 2:
/* Function Definition */
return-type function-name(datatype &p1[, datatype &p2, …])
{
}
main( )
{
16 of 20
---
function-name(p1[,p2,…]); /* Function Call */
---
}
Following examples show how call by reference may be used for swapping
of two variables.
Example 2:
/* program for swapping of two variables (call by reference with syntax 1) */
main( )
{
int x,y;
void swap(int*,int*);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping: x = %d, y = %d\n”,x,y);
swap(&x,&y); /* here references of x and y are passed */
printf(“After swapping: x = %d, y = %d\n”,x,y);
}
/* Due to call by reference, x & a are same and y & b are same */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
Please enter two numbers: 85 64
Before swapping: x = 85, y = 64
After swapping: x = 64, y = 85
Example 3:
/* program for swapping of two variables (call by reference with syntax 2) */
main( )
{
int x,y;
void swap(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping: x = %d, y = %d\n”,x,y);
swap(x,y);
printf(“After swapping: x = %d, y = %d\n”,x,y);
}
/* Due to call by reference, x & a are same and y & b are same */
17 of 20
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Please enter two numbers: 39 71
Before swapping: x = 39, y = 71
After swapping: x = 71, y = 39
int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return (n*fact(n-1));
}
}
Recursive call stops when n become 0. For this example, n=0 is exit
condition of recursion. Complete program for using above function is shown
below.
Example 1:
/* Consider long int as return type because 8!=40320 which is out of range
of int. Same is the case for all the numbers above 8. */
long int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return (n*fact(n-1));
}
}
main( )
{
int x;
printf(“Enter a number whose factorial is to be found: ”);
scanf(“%d”,&x);
printf(“%d! = %ld ”,x,fact(x));
}
Output:
Enter a number whose factorial is to be found: 6
6! = 720
Sample Questions
20 of 20