You are on page 1of 13

SCA Pvt Ltd.

(Sharma Computer Academy)


Author: Saurabh Shukla

Chapter-8
Functions
Introduction
Functions are basic building blocks of program where we write our code.
We can assume any C program is collection of several function.
Till now we write our code in main function. In all our previous programs, we used to
create only one function that is main().
Modularization
Modular programming is a software design technique that increases the extent to which
software is composed of separate, interchangeable components, called modules by
breaking down program functions into modules, each of which accomplishes one
function and contains everything necessary to accomplish this
Suppose a C program is designed to perform a task. And say this task can be divided into
few subtasks, each of which is independent functionality. Each subtask can be coded in a
separate block known as function.
Program Execution always starts from main(). Main can then call other function. Any
function can call other function. This call is an invitation to that function to perform its
subtask.
Technical terms
l Calling Function: Function who call another function
l Called Function : Function who is called by another function
l Function call: Action of calling a function
You have been using few functions from the starting of programming. For example
printf(), scanf(), clrscr() and getch(). These are all functions and you often call them to
perform task for which they are designed.
There are many more such functions. These are predefined functions. There code kept in
library files. These files are comprehensively called built-in C library.
Function Types
There are two types of functions:
1) Predefined Functions
2) User defined Functions

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
C library is a very rich source of built in functions. You can use them as per your need.
First we should look user defined functions. As the name suggests, these are not available
in C library, it is our job to define them. As a programmer we have to identify how many
functions we have to write to solve a problem. Logically each subtask should be handled
by a separate function.
Creating function is just writing code (set of statements), wrap them in curly braces
(block), and give a name to the block to identify this code block. This name is called
function. You can chose name of the function. Giving name to a code block has same
rules as the variable name has. Only alphabet, digits and underscore can be used in
function name formation.
Example: Understand the program flow.
main()
{
printf(\nI am in function main() );
a();
printf(\nI am in function main() );
b();
printf(\nI am in function main() );
a();
printf(\nI am in function main() );
}
a()
{
printf(\nI am in function a() );
}
b()
{
printf(\nI am in function b() );
a( );
}
Output
I am in function main()
I am in function a()
I am in function main()
I am in function b()
I am in function a()
I am in function main()
I am in function a()
I am in function main()
Although you can easily understand above program by observing output, but few things
are worth mentioning here:

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
1) Program execution always begin with function main()
2) Any function comes in action whenever it is called.
3) Once a function finished its job control returns at the place from where the
function is called.
4) Function gets memory in RAM whenever it is called. Memory releases as the
function finishes all its instructions.
10 Basic Questions
1)
Ans:

Can we call a function several times in a single program?


Yes.

2)
Ans:

Can user define function become a calling function?


Yes.

3)
Ans:

Can we pass values through functions?


Yes, it is called Call by value.

4)
Ans:

Can we have a c program without main function.


No

5)
Ans:

Is there any limit of total number of functions that can c programs have?
No

6)
Ans:

Can two functions have same name with different definitions?


No

7)
Ans:

Who calls main?


An operating system.

8)
Ans:

Can a function call main() ?


Yes

9)
Ans:

Can a function call itself ?


Yes, it is called recursion.

10)

Why write separate functions at all? Why not squeeze the entire logic into one
function main()?
Writing functions avoids rewriting the same code over and over.
It provides strong readability.
It makes program easy to debug.
It becomes easy to modify.
Better memory utilization

Ans:

Function call can be categorized as:


l
l
l
l

Takes nothing return nothing


Takes something returns nothing
Takes nothing returns something
Takes something and returns something

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
Second and fourth from the above are comes under function call by value, as we pass values
during function call. Each of the above mentioned style can be easily understood with the
following examples:
Takes nothing returns nothing
void sum()
{
int a,b,c;
printf(Enter two numbers:-);
scanf(%d%d,&a,&b);
c=a+b;
printf(Sum is %d,c);
}
main()
{
void sum(void);
clrscr();
sum();
getch();
}
Explanation:
1) In this program we wrote two functions, one is sum() and second is main().
2) It is not necessary to define sum() before main(). There would be no difference in, what
order of function definition is positioned in your program. This is completely a
programmer choice. Whatever may the order of function definition, program execution
always starts from main().
3) Notice the first line of main() function (void sum;). This is called declaration of function.
Declaration of function tells the compiler about return type, function name and argument
type. Since we are not returning any value we mentioned so by void. Function name is
sum. Since there is no argument we mentioned it so by using keyword void in the
parenthesis. We will discuss more about function declaration later in this chapter.
4) Second line in the main function is a call to a predefined function clrscr(). Since clrscr()
function defined in such a way that it takes nothing, we left its parenthesis empty.
5) Next line is a call to a function sum(). This function takes nothing, so the parenthesis is
empty. Due to call to function sum(), control moves to the definition of function sum(). In
sum(), three int type variables are declared. After call to printf() and scanf(), c is assigned
a value which is an addition of value stored in a and b. Lastly the call to printf() displays
the result.
6) When all the statements of function sum() worked out, control returns back from where
sum() was called. Hence control comes back to main() and the last function getch()
execute.
Takes something returns nothing
void sum(int x, int y)
{
int c;

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
c=x+y;
printf(Sum is %d,c);
}
main()
{
void sum(int, int);
int a,b;
clrscr();
printf(Enter two numbers:-);
scanf(%d%d,&a,&b);
sum(a, b);
getch();
}
Explanation:
1) This time we passed two int type values during call to function sum(a,b). these values are
called actual arguments or parameters.
2) Notice the subsequent change in function declaration and definition.
3) Values of a and b are collected in x and y. Variable x and y are called formal arguments.
4) It is important to note that any function can access only those variables that are declared
in their body. So the scope of variable is limited to the function in which it is declared.
Takes nothing returns something
int sum()
{
int a,b,c;
printf(Enter two numbers:-);
scanf(%d%d,&a,&b);
c=a+b;
return(c);
}
main()
{
int sum(void);
int s;
clrscr();
s=sum();
printf(Sum is %d,s);
getch();
}
Explanation:
1) In this example we do not pass anything but function sum returns an int type value, which
is addition of two numbers. Notice the change in return type in function declaration and
definition part. Also notice how we collect the return value in function main. Whatever
sum() returns, it goes back at the same place from where a function is called. It is then
assigned to s.

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
2) The keyword return is used to return value of any type. We can only return single value
using return.
3) As soon as return is executed control comes back to the calling function, thus it is
meaning less to expect any statement could execute after return in function sum().
Takes something returns something
int sum(int x,int y)
{
int c;
c=x+y;
return(c);
}
main()
{
int sum(int,int);
int s;
clrscr();
printf(Enter two numbers:-);
scanf(%d%d,&a, &b);
s=sum(a,b);
printf(Sum is %d,s);
getch();
}
Explanation:
1) This time function sum() is called by passing two int values and addition is returned back
to calling function.
Another example:
1) Program to calculate area of a circle.
float area(int);
main()
{
int r;
float a;
clrscr();
printf(Enter radius of circle:-);
scanf(%d,&r);
a=area(r);
printf(Area of circle is %f ,a);
getch();
}
float area(int r)
{
float A;
A=3.14*r*r;
return(A);

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
}
Understand by yourself.
Function prototype
Function prototype also known as function declaration. Although you have already seen how
functions has to be declared. Here we would like to throw some light on function declaration.
1) In C language, function declaration is recommended but not mandatory. Some of the
compiler allow programmer to use function without declaration, but we recommend to
declare all functions used in your program. It is so because subsequent languages
including C++ are very strict about function declaration.
2) Function prototype has general form:
return type function name ( argument type);
3) All predefined functions are already declared and there declaration is kept in some header
file, all you need to include that header file. For example printf() and scanf() functions
are declared in stdio.h. Similarly, clrscr() and getch() are declared in conio.h

Recursion
Function calling itself is called recursion.
Example:
int fun(int );
main()
{
int x, k=3;
x = fun (k);
printf(%d, x);
}
int fun ( int a)
{
int f;
if (a == 1) return(1);
f = 2 + fun (a 1);
return(f);
}
The output is
5
Explanation:
Operating system calls main() function. Memory for x and k are being allotted. k is assigned with
3. Now fun() is called by main() and passes value of k(called by value). Memory for the function
fun(3) is allotted, in which there are two variables f and a. a contains 3.
Now condition a==1 is false so control moves on f=2+fun(a-1). Here, again make a call to
function fun(). fun() is calling fun(), this is called recursion.
Remember this time a new and separate memory is being allotted, call it fun(2). It also uses the
same definition but its variable a contains 2. The condition a==1 is again false. And again control
moves to f=2+fun(a-1). Again function fun(1) is called from fun(2) and recursion continues.

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
Again separate memory is allocated for fun(1). This time a would contain 1 and the condition
a==1 is true and return(1) to the calling function that is fun(2). You can easily understand these
successive returns to the calling functions.
At last x would contain 5.
Discussion about few predefined functions
getch()

It reads a character and never wait for Enter key.Just gets processed after getting any key
pressed.And it never echoes the character on screen which u pressed.
getche()

it works same as getch() but it echoes on screen.


getchar()

Whenever you are pressing any key then the these are kept in Buffer. After hitting enter
the first character gets processed. And it obviously echoes on the screen.
Formatting with printf()

"printf" writes formatted output to "stdout". The result of "printf" is the number of
characters written. The output is formatted according to the "format" string. This string
may contain two kinds of objects:

ordinary characters which are simply copied to "stdout";


placeholders, which tell "printf" how to format arguments in the variable
argument list.

Each placeholder starts with the character '%' and ends with one or two letters that
indicate what "type" of formatting is necessary.
Between the '%' and the "type" field may appear "modifiers", "width", and "precision"
fields. An ANSI placeholder has the form
%[modifiers][width][.precision]type

where square brackets indicate that a field is optional.


The type field
d
i
c
f
ld
lf
Lf

decimal integer
integer
character
float
long integer
double
long double

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
u
lu

unsigned int
unsigned long int

The modifiers field

The modifiers field consists of zero or more characters that indicate how output should be
padded (e.g. whether numbers are preceded by blanks or leading zeros), and whether or
not '+' or '-' signs are printed.
- (minus) indicates that values should be left-justified. The default action is to rightjustify them.
The width field

The width field is a non-negative decimal integer giving the minimum number of
characters to be printed
If the output value is shorter than the given width, it is padded to the appropriate width by
putting blanks on the right (or on the left, if the '-' "modifier" character is specified).
With numeric placeholders, the number in the width field may have a leading 0. With
this, the output value will be expanded with zeros to give the number the specified width.
For example, with "%05d" the value -1 will be printed as "-0001".
The width field can also be the character '*', in which case "printf" will take the next
argument in the argument list and take that as the width value. For example,
printf("%*d",4,X);

prints the value of X with a width of 4. Note that the width value is obtained from the
argument list BEFORE the output value is obtained.
The precision field

The precision field is a dot '.' followed by a non-negative decimal integer. Its meaning
depends on the "type" field as given below.
If the "type" is 'd', 'o', 'u', 'x' or 'X', the precision number is the smallest number of
digits that may appear in the output value. If necessary, the number will be padded on the
left with leading zeros. If the precision number is 0 or the field is just a '.' with no number
following, an output value of 0 will result in no characters being printed.
If the "type" is 'e', 'E', or 'f', the precision number is the number of digits printed after
the decimal point. If the precision number is 0 or the field is just a '.' with no number
following, no decimal point is printed.
The precision field can also be the character '*', in which case "printf" will take the next
argument in the argument list and take that as the precision value. For example,
printf("%*.*f",8,3,Y);

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
prints the value of Y with a width of 8 and a precision of 3.
Input with scanf()
If you have multiple format specifiers within the string argument of scanf, you can input multiple
values. All you need to do is to separate each format specifier with a DELIMITER - a string that
separates variables. For convenience, the delimiter should be one character that's a punctuation
mark, like a comma or a space.
As a default, scanf stops reading in a value when space, tab or Enter is pressed.
We can mention other delimiters too.
scanf(%d,%d,%d,&a,&b,&c);
scanf(%d:%d:%d,&a,&b,&c);
scanf() will generally line-buffer input when the %c specifier is used. This makes it somewhat
troublesome
Although spaces, tabs, and newlines are used as field separators when reading other types of data,
when reading a single character, white-space characters are read like any other character

scanf(%c%c%c,&a,&b,&c);
For testing our input is qwe
q is stored in a, w is stored in b and e is stored in c.
scanf(%c%c%c,&a,&b,&c);
For testing our input is: q w e
q is stored in a, space is stored in b and w is stored in c.
This is because white-space characters are read like any other character
scanf(%c%c%c,&a,&b,&c);
For testing our input is: q enter
q is stored in a, space is stored in b
w enter
w is stored in c.
scanf(%c %c %c,&a,&b,&c);
For testing our input is: q enter
q is stored in a, space is a delimiter
w enter
w is stored in b, space is a delimiter
e enter
e is stored in c.
scanf(%c %c %c,&a,&b,&c);
For testing our input is: q w e

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
q is stored in a, space is a delimiter, w is stored in b, space is a delimiter, e is stored in c
scanf(%c,%c,%c,&a,&b,&c);
For testing our input is: q,w,e
q is stored in a, comma is a delimiter, w is stored in b, comma is a delimiter, e is stored in c
Input Using Scanset
The scanset conversion facility provided by scanf ( ) is a useful string input method. This conversion
facility allows the programmer to specify the set of characters that are ( or are not) acceptable as part of the
string. A scanset conversion consists of a list of acceptable character enclosed within square brackets. A
range of character may be specified using notations such as a z , meaning all character within this range.
The actual interpretation of a range in this context is implementation specific, i.e., it depends on the
particular character set being used on the host computer if an actual is required in the scanset, it must
be the first or last character in the set if the first character after the [ is a ^ character, then the rest of the
scanset specifies unacceptable characters rather then acceptable characters.
The following program shows the use of scansets.
main ( )
{
char str [50];
printf (Enter a string in lower case );
scanf ( % [ a z ] , str ) ;
printf ( the string was : %s /n , str);
}
There sample runs are given below.
(i)
Enter a string in lower case hello world the string was : hello world
(ii)
Enter a string in lower case hello, world the string was : hello
(iii)
Enter a string in lower case abcd234 the string was : abcd
Note that in all cases, conversion is terminated by the input of something other than a space or lowercase
letter. The circumflex ( ^) plays an important role while taking input.
SINGLE LINE INPUT USING SCANSET
For a single line text input, the user presses the < Return > or < Enter> key to terminate the string. The
maximum number of character typed by the user might be 80 because the screen can print a maximum of 80
character. All character are allowed to be typed as input except /n . the computer takes this ( /n) as a clue
indicating that the string has ended. Look at the example given below.
# include < stdio . h >
main ( )
{
char str [ 80] ;
printf ( Enter a string in lower case );
scanf ( % [^ /n , str);
printf ( the string was : %s /n , str
}

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
MULTILINE INPUT USING SCANSET
One can use a bracketed string read, % [ . .] where the square brakets [ ] are used to enclose all character
which are permissible in the input. If any character other than those listed within the brackets occurs in the
input string, further reading is terminated. Reciprocally, those characters may be specified with the brackets
which if found in the input, will cause further reading of the string to be terminated. Such input terminators
must be preceded by the caret (^). For example if the tide (~) is used to end a string the following scanf ( )
shows how it is coded.
char string [200] ;
scanf (% [ ^ ~] , string ) ;
then if the input for string consists of embedded spaces, no matter what they will all be accepted by scanf (
); and reading will stop when a tilde ( ~) is entered. This is illustrated in the following program and its
output.
# include < stdio.h >
main ( )
{
char string [ 80] ;
printf ( Enter a string terminate with a tilde (~) );
scanf ( % [^ ~] , string );
printf (%s, string);
{
Output
Enter a string , terminate with a tilde (~) . . . I am a string . ~ I am string
Though the terminating tilde is not itself included as an elements of the string read it stays in the read buffer
the area of memory designated to store the input and will be picked up by the next call to scanf ( ) , even
though it is not required. This is illustrated by the following program and its output. Here when the second
call to scanf ( ) is executed automatically, the tilde ( ~) character is assigned to the character variables x .
the call putchar ( ) prints the value of x.
# include < stdio .h >
main ( )
{
char string [80];
char x;
printf ( Enter a string terminate with a tilde (~) . . .);
scanf (% [^ ~] , string );
scanf (%c , &x) ; / * the leftover from the last scanf wait for you to enter another char .*/
printf (%s , string ) ;
putchar (x) ;
}

Output :
Enter a string terminate with a tilde (-) . . . t am a string
I am a string.

SCA Pvt Ltd. (Sharma Computer Academy)


Author: Saurabh Shukla
Compile and execute the program. It will be found that the machine executes the second scanf( )
without much fuss. Such dangling characters must be absorded away by a subsequent call to scanf( ) with
%c, or to getchar( ) or they may interfere in unexpected ways with subsequent calls to scanf( ) or getchar( ).