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:
► Calling Function: Function who call
another function
►Called Function : Function who is
called by another function
► 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
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:
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) Can we call a function several times in a single program?Ans: Yes.
2) Can user define function become a calling function?Ans: Yes.
3) Can we pass values through functions?Ans: Yes, it is called “Call by value”.
4) Can we have a c program without main function.Ans: No
5) Is there any limit of total number of functions that can ‘c’ programs have?Ans: No
6) Can two functions have same name with different definitions?Ans: No
7) Who calls main?
Ans: An operating system.
8) Can a function call main() ?
Ans: Yes
9) Can a function call itself ?
Ans: Yes, it is called recursion.
10) Why write separate functions at all? Why not squeeze the entire logic into one function main()?
Ans: 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
Function call can be categorized as:
► Takes nothing
return nothing
► Takes something
returns nothing
► Takes nothing
returns something
► Takes something
and returns something
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;
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.
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);
}
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. 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.
few predefined functions:
Formatting with
printf()
Input with scanf()
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
}
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. –
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( ).
No comments:
Post a Comment