Documente Academic
Documente Profesional
Documente Cultură
net/publication/283508475
CITATIONS READS
0 1,721
1 author:
Rama M A
Maharani Lakshmi Ammanni College for Women
11 PUBLICATIONS 61 CITATIONS
SEE PROFILE
All content following this page was uploaded by Rama M A on 06 November 2015.
Library functions are built-in functions and are ready to use. These functions need
not be written by the user. However, user-defined functions must be developed by the user.
The need for writing user-defined functions arises due to the following reasons:
1. When the same set of statements must be repeated several times in various
parts of a program, these statements can be placed in a function and invoked
wherever required.
2. When user-defined functions are used in a program, the number of lines of code
decreases incredibly.
o data-type denotes the data type of the result returned by the function. If this
return data type is omitted in the declaration, it is assumed to be int. In general
the return data types are int, float, char or void (null).
o function-name represents the name of the function. It follows the same rules of
formation as variable names in C.
o Argument list is the list of variables or arguments within parenthesis separated
by commas. There is no semi colon after the closing parentheses.
o argument declaration is of the form:
type1 arg1, type2 arg2, ... typen argn; where type1, type2, .... represent the data
types of the arguments arg1, arg2,.... argn. These argument variables must be the same as
those listed in the argument list. For example,
add (n1, n2)
int n1, n2; //argument declaration
{
.........
}
This type of declaration is done in the old method known as the classic method.
The new method or the ANSI method continues the argument declaration in the function
header as follows:
Since most of the modern compilers support both methods, the function header can
be declared using either of the above. The ANSI method of declaration will be followed in
this book.
o Local variables are declared only when needed. These variables are local to the
function in which they are declared.
FUNCTIONS 179
o Body of the function contains the executable statements and the local
variables if any, required to perform the task.
o return statement issued to return the resultant value of the function to the
calling program. The expression contains the returned value.
Example 4.1
/*Function to add two numbers */
int add(int a, int b) /* function header with arguments */
{
int sum; /* Local variable */
sum=a+b; /* Executable statements */
return(sum); /* value of sum returned to main program */
}
Example 4.2
/*FUNCTION TO FIND MAXIMUM OF 3 INTEGERS*/
int maxi(int a, int b, int c)
{
int big;
big=a;
if(b>big) big=b;
if(c>big) big=c;
return(big);
}
Variable=function_name(argument list);
Example 4.3
/*Program to show Referencing of a Function*/
#include<stdio.h>
void main()
{
int result,a,b;
clrscr();
180 PROBLEM SOLVING TECHNIQUES USING C
Output
Enter 2 numbers:
4 16
Sum of 4 and 16 = 20
or
printf (“\n Sum = %d”, add (a, b);
However a function must not be used on the LHS of an assignment statement such
as
add (a, b) = x; //Error
which is invalid.
When the main program calls the function add ( ) control is transferred to the
function add ( ) and the values are transferred as:
result = add (a , b);
4 16
add (int a , int b)
The transfer of control and the values, between the main program and the function
can be shown diagrammatically:
FUNCTIONS 181
main ( )
{
int a = 4, b = 16;
............
20
result=add (a, b);
..............
.............
} (4, 16)
i) The first form of return (without expression) is used when the function does not
return any value to the calling function. In such a case it is used to exit from the
function. For example,
if (n < 1)
return;
ii) The second type of return statement returns the value of the expression. In example
4.3 the function add( ) returns the value of sum to the main program. The expression
within parentheses can be a numeric constant, variable or an expression. For
example
add (int a, int b)
{
int sum;
sum = a + b;
return (sum);
}
or
182 PROBLEM SOLVING TECHNIQUES USING C
if (prime = = 1)
return (1);
else
return (0);
Where return-data-type denotes the data type of the value returned by the
function, function-name represents the name of the function and type1, type2....
represent the data types of the arguments arg1, arg2,.... argn.
o One difference between a function definition and a function prototype is that a
function prototype ends with a semicolon.
o The names of the arguments within function prototype can be used elsewhere in
the program since these are dummy argument names which are local to the
function prototype. In fact the argument names can be omitted. However the
argument type is essential.
For example function prototype add can be declared as:
FUNCTIONS 183
o The data types of the actual arguments must match the data types of the
arguments within the prototype.
o Function prototypes are not compulsory, but desirable, since they facilitate error
checking.
Example 4.4
/*Program to find the Factorial of a Number Using Function */
#include<stdio.h>
void main()
{
long factorial(int n); // Function prototype
/*Function declaration*/
long factorial(int n)
{
long fact=1;
int i;
for(i=1;i<=n;i++)
fact=fact*i;
return(fact);
}
Output
Enter an integer number Please:
5
Factorial of 5 = 120
3. The number and type of arguments which the function has to handle, i.e, one
argument of type int.
main( )
{ Actual Parameters
:
a=10, b=5;
result=add (a, b);
10 5
}
add (int a, int b) //Function declaration
{
............
............ Formal
............ Parameters
}
Example 4.5
/*Program to check for Prime Number using a Function*/
#include<stdio.h>
int prime (int); /*function prototype*/
void main()
{
int n;
clrscr();
printf("\n Type an integer please: ");
scanf("%d",&n);
if(prime(n)==1) // n is actual parameter
printf("\n %d is Prime", n);
else
printf("\n %d is not Prime",n);
}
Output
Type an integer please: 17
17 is Prime
Type an integer please: 28
28 is not Prime
186 PROBLEM SOLVING TECHNIQUES USING C
main ( )
{
......
.........
printhead( );
.........
.........
}
FUNCTIONS 187
printhead( )
{
printf (“\n Maharani Lakshmi Ammanni College \n”);
return;
}
Similarly return statement is optional since the function does not return any values.
Further the function call must be written as an independent statement, since it does not
return any values to the calling program.
Example 4.6
void printline()
int j;
for(j=1;j<=42;j++)
188 PROBLEM SOLVING TECHNIQUES USING C
printf("%c",'*');
printf("\n");
}
Output
MAHARANI LAKSHMI AMMANNI COLLEGE FOR WOMEN
*****************************************
main ( )
{
print head1 ( );
print head2 ( );
print line( );
return; No arguments
}
}
No arguments
void print head2 ( )
{
........
........
No return
values void printline ( )
{
........
........
The working of such lfunctions with no data communication can be illustrated with a
diagram as shown in figure 4.3.
FUNCTIONS 189
void main ( )
{
.........
.........
fun (n);
........
........
}
Passing
No return argument n
values void fun (int n)
{
........
........
}
Example 4.7
/*Program to find area of a triangle using a function tri with sides as its arguments*/
#include<stdio.h>
#include<math.h>
tri(float,float,float); // function prototype
void main()
{
float a,b,c;
clrscr();
printf("\n Enter the 3 sides of a triangle: ");
scanf("%f %f %f",&a,&b,&c);
/*Calling the function tri with argument a,b&c*/
tri(a,b,c);
}
190 PROBLEM SOLVING TECHNIQUES USING C
Output
Enter the 3 sides of a triangle: 3 4 5
Area of triangle = 6.000000
void main ( )
{
.........
.........
x = fun (n)
........
........
}
Passing
Return argument n
value ans int fun (int n)
{
........
........
return (ans)
}
Generally the result of the function is not displayed within the function since it may
be required for further calculations in the calling program. Further for modular
programming, a function must not contain any input/output operations. Moreover the
result may have to be displayed in different formats in different calling programs.
Therefore, the resultant value from the function is returned to the calling function, where
it can be used as needed. This type of functions have two-way data communication as
shown in figure 4.5.
FUNCTIONS 191
Example 4.8
/*Program to find the sum of first n natural numbers using a function with
Arguments and Return Value*/
#include<stdio.h>
int sum(int n); //function prototype
void main()
{
int n,i,total;
clrscr();
printf("\n How many numbers ? ");
scanf("%d",&n);
/*Calling function sum*/
total=sum(n);
printf("\n Summation fo first %d numbers = %d", n, total);
}
Output
How many numbers ? 10
Summation of first 10 numbers = 55
o In the above example when the function sum is called, control is transferred to
the function with copies of the actual parameter n.
o Next the formal argument m is assigned the value of n passed from the main
function.
o After executing the statements in the function, the result is sent back to the
calling function through the return statement.
o Now the calling statement is executed by assigning the returned value to
total.
192 PROBLEM SOLVING TECHNIQUES USING C
Example 4.9
/*Program to find x^n where x is real and n is integer - using function*/
#include<stdio.h>
float power(float,int); //function prototype
void main()
{
int n;
float x,pr;
clrscr();
printf("\n Type the value of x and power n: ");
scanf("%f %d",&x,&n);
pr=power(x,n);
printf("\n Result = %7.3f",pr);
}
Output
Type the value of x and power n: 2 5
Result = 32.000
Type the value of x and power n: 2 –3
Result = 0.125
FUNCTIONS 193
void main( )
{
large = max( );
} no arguments
return value
ans int max( )
{
return (ans);
}
Example 4.10
/* Program to illustrate function with no arguments but with return value */
#include <stdio.h>
void main()
{
int large;
large = max();
printf("\n The largest value is : %d ", large);
getch();
}
/*Function to find MAXIMUM of 3 integers */
int max()
{
int big,a,b,c;
clrscr();
printf("\n Enter the values of a b and c : ");
scanf("%d %d %d" , &a , &b , &c );
big = a;
if(b > big) big = b;
194 PROBLEM SOLVING TECHNIQUES USING C
Output
Enter the values of a b and c : 12 45 8
The largest value is : 45
void main ( )
{
..........
..........
fun1 ( );
..........
fun2 ( );
..........
fun1 ( );
..........
fun3 ( );
..........
}
/*Function fun1*/
fun1 ( )
{
..........
..........
}
/*Function fun2*/
fun2 ( )
{
..........
..........
}
/*Function fun3*/
fun3 ( )
{
..........
..........
}
Example 4.11
/*Program to find lcm and gcd of two integers using a function to compute
gcd and lcm */
#include<stdio.h>
int gcd(int,int); //function prototypes
int lcm(int,int);
void main()
{
int result1,m,n,result2;
clrscr();
printf("\n Type the two integer numbers: ");
scanf("%d %d",&m,&n);
result1=gcd(m,n); /*function call to gcd() */
result2=lcm(m,n); /*function call to lcm() */
printf("\n GCD = %d",result1);
printf("\n LCM = %d",result2);
}
ans=(m*n)/gcd(m,n);
return(ans);
}
Output
Type the two integer numbers: 6 12
GCD = 6
LCM = 12
In the above example the main function calls the function gcd( ) and function lcm( ).
The function lcm( ) calls gcd( ) within itself.
Example 4.12
/* Program to illustrate Passing Arguments to Functions */
#include <stdio.h> Memory allocated
for main program
void main()
{ 100
int a=100; a
clrscr();
printf("\nBefore calling function a = %d",a);
Memory allocated
sample(a);
for function
printf("\nAfter calling function a = %d",a);
} 300
void sample(int a) a
{ After changing the value
a= a* 3;
printf("\nWithin the function a = %d",a);
}
Output
Before calling function a = 100
Within the function a = 300
After calling function a = 100
FUNCTIONS 197
The output shows that the value of 'a' is not altered in main( ) even though its value
is changed within the function sample. This is due to the fact that the called function gets
only copies of the actual arguments which are created when control passes to the function
and are destroyed when control returns to the calling program.
fun (int x)
{
.............
.............
y = fun(x);
............
.............
}
Example 4.13
/*Program to calculate factorial of an integer using recursion*/
#include<stdio.h>
long fact(int n); /*function prototype*/
void main()
{
int num;
clrscr();
printf("\n Type a number please: ");
scanf("%d",&num);
198 PROBLEM SOLVING TECHNIQUES USING C
Output
Type a number please: 4
Factorial of 4 = 24
When a recursive program is executed, the recursive function calls are not executed
immediately but placed on a stack until the termination condition is encountered. Next the
function calls are executed in reverse order and the result returned to the calling function.
In the above example consider the function call for the value 4.
fact (4)
(4*fact(3))
(3*fact(2))
(2*fact(1))
1 (terminating condition)
returns
2*1=2
3*2=6
4*6=24
Example 4.14
The recursive statement to find the sum of first n natural numbers can be written
as follows:
if (n = = 0)
return 0;
else
return ((n + sum (n - 1));
Output
Enter the value of n: 25
Sum of first 25 natural numbers = 325
200 PROBLEM SOLVING TECHNIQUES USING C
Example 4.15
/*Function to calculate gcd fo two integers */
#include<stdio.h>
int gcd(int m,int n); //function prototype
void main()
{
int m,n;
clrscr();
printf("\n Enter two integers :");
scanf("%d %d", &m,&n);
printf("\n GCD of %d and %d = %d", m,n,gcd(m,n));
}
Output
Enter two integers: 6 12
GCD of 6 and 12= 6
Program Name
A B C
A1 A2
The concept of top-down is shown by the sub-function called Process. The main
program (Program name) consists of 3 sub-functions – initialize, process and EndofJob.
The main program first calls Initialize, next process and finally EndofJob. When
process is called its calls A, B and C in turn. Function B does not run until A is done.
While A is running it calls A1 and A2 in turn. This means that all functions in a line from
process to A2 must be called before function B can start running.
Structure charts show only the function flow of the program. They do not contain
any code.
For example :
4. It is an error to use void as return type with a function that expects a return
value or vice versa.
5. It is a logical error to code the parameters in the wrong order. Their meaning
will be inconsistent in the called program.
6. Do not forget the semicolon at the end of a function declaration. However using a
semicolon at the end of the header in a function definition is a compile error.
7. It is a run-time error to write a function call without the parentheses, even when
the function has no parameters.
REVIEW QUESTIONS
19 Give the general syntax of functions with no arguments and no return values.
20. Give the general syntax of recursive function.
21. What are sub-programs? What are their advantages and disadvantages?
22. Show the use of functions without arguments and without return values with a
suitable example.
23. Explain the working of functions with arguments and no return values.
24. Show the use of functions with arguments and with return values with a suitable
example.
25. Give the output of the following program:
void main ( )
{
int a, count;
int func (int count);
for (count= 1; count < = 5; ++count)
{
a = func (count);
printf (“%d”, a);
}
}
int func (int x)
{
int y = 0;
y + = x;
return (y);
}
n!
nC =
r r!(n r)!
Use a function to calculate factorial.
Write a program using function to:
2. Output the rightmost digit of a numbers.
3. Add, subtract and multiply two complex numbers.
4. Find the GCD and LCM of two numbers.
5. Generate prime numbers in a range.
6. Find whether a given number is an Armstrong number
(Example 153 = 13 + 53 + 33 = 153)
204 PROBLEM SOLVING TECHNIQUES USING C
__________