Professional Documents
Culture Documents
Functions
6.1 Introduction
A function is a single comprehensive unit (self-contained block) containing blocks of statements
that performs a specific task. The specific task is repeated each time when the function is called.
So, this avoids the need of rewriting the same code again and again. Every program must contain
one function named main() from where the program always begin execution.
As real world applications become more complex and large, several problems arise. Most
common problems are:
Algorithms for solving more complex problems become more difficult and hence difficult
to design.
Even after designing an algorithm, its implementation becomes more difficult because of
the size of the program.
As programs become larger, testing, debugging, and maintenance will be a difficult task.
Thus, complex problems can be solved by breaking them into a set of sub-problems, called
Modules or Functions. This technique is called divide and conquer. Each module can be
implemented independently and later can be combined into a single unit. C function offers the
following advantages:
Top-down modular programming: Modularity facilitates logical clarity on programs
Avoids redundant code: The repeated instructions can be written as a function, which can
then be called whenever it is needed
Code reusability: The functions created in one program can be accessed in other programs.
C functions can be used to build a customized library of frequently used routines.
C supports modularity by means of functions. C functions are classified into two categories.
Library functions: The library function does not required definition to be written by
user. Such function may be: printf(), scanf(), gets(), puts(), etc.
User defined functions: The user defined function has to be developed by the
programmer at the time of writing the program. Such function may be: main(), nast() for
printing the message “National Academy of Science and Technology” etc.
When a function is called, the program execution is shifted to the first statement in the called
function. After the function returns to the calling function, values can be returned and that value
can be used as an operand in an expression. For example:
#include<stdio.h>
#include<conio.h>
int DEC(void);
void main() //Calling function
{ DEC(); //Called function
printf("\n NAST");
DEC(); //Called function
getch();
}
DEC() //Function defination
{
printf("\nDhangadhi Engineering College");
}
Output: Dhangadhi Engineering College
NAST
Dhangadhi Engineering College
Syntax:
return_type function_name(parameter list )
{
body of the function
}
For example:
void starline()
{
int i;
for(i=0;i<10;i++) Local declaration
printf("* \t")
}
If we define the data type of function globally (i.e. outside the main () function), it is
called the global declaration of function or prototype. Function prototyping means
writing the function prototypes before their function call occurs. A function prototype
is a declaration of the function that tells the program about the type of the value
returned by the function and the number and type of the arguments. The prototyping
is mandatory in C to ensure proper invocation of functions and prompt error reporting.
Argument
The mechanism used to convey information to a function is the argument. The arguments are of
two types: Actual arguments and Formal arguments. Arguments defined inside the function are
called formal arguments whereas the argument from which the arguments have been passed to a
function is known as actual arguments.
For example:
#include <stdio.h>
#include <conio.h>
void printline (char); //prototype declaration
void calsum (int, int); //prototype declaration
void main()
{
int a, b; // a and b are actual arguments
clrscr();
printf("Enter two numbers:");
scanf ("%d %d",&a,&b);
printline ('*');
calsum (a, b);
printline ('#');
getch();
}
With no return value and no argument With no return value but having argument
void add(void); void add(int,int);
void main() void main()
{ {
clrscr(); int a,b;
add(); clrscr();
getch(); printf("Enter value of a:");
} scanf("%d",&a);
void add(void) printf("Enter value of b:");
{ scanf("%d",&b);
int a,b,c; add(a,b);
printf("Enter value of a:"); getch();
scanf("%d",&a); }
printf("Enter value of b:"); void add(int x, int y)
scanf("%d",&b); {
c=a+b; int c;
printf("Value of c is:%d",c); c=x+y;
} printf("Value of c is:%d",c);
}
With return value but no argument With return value and with argument
int add(void); int add(int,int);
void main() void main()
{ {
int x; int a,b,x;
clrscr(); clrscr();
x=add(); printf("Enter value of a:");
printf("Value of c is:%d",x); scanf("%d",&a);
getch(); printf("Enter value of b:");
} scanf("%d",&b);
int add(void) x=add(a,b);
{ printf("Value of c is:%d",x);
int a,b,c; }
printf("Enter value of a:"); int add(int x, int y)
scanf("%d",&a); {
printf("Enter value of b:"); int c;
scanf("%d",&b); c=x+y;
c=a+b; return c;
return c; }
}
2. It returns the value present in the parenthesis after return to the calling function.
3. A function can return only one value at a time. Thus, the statement return (a, b); is invalid.
4. The return statement without any value i.e. return; , returns the garbage value to the calling
function because we are not returns with any specific value so we usually write: return(0);.
5. There is no restriction on the number of return statements that may be present in the function.
6. If the value of a formal argument is changed in the called function, the corresponding change
does not take place in the calling function.
For example:
#include<stdio.h>
#include<conio.h>
int function(int);
void main()
{
int a = 30;
function (a);
printf ("%d", a);
getch();
}
function (int b) Output: 60
{ 30
b = 60;
printf ("%d \n", b);
}
It means that when values are passed to a called function, the value present in actual
argument are not physically moved to the formal argument, just a photocopy of values in
actual argument is mode into formal argument.
int sqr(z)
int z;
{
return (z*z);
}
void lalitpur()
{ printf("I'm inside lalitpur\n");
}
Directive Description
#define Substitutes a preprocessor macro
#include Inserts a particular header from another file
#undef Undefines a preprocessor macro
#ifdef Returns true if this macro is defined
#ifndef Returns true if this macro is not defined
#if Tests if a compile time condition is true
#else The alternative for #if
#elif #else an #if in one statement
#endif Ends preprocessor conditional
#error Prints error message on stderr
#pragma Issues special commands to the compiler, using a standardized method
Macro
Macro is a preprocessor which hold the value of any constant so it is also called symbolic
constant. It is globally declared before the main functions. On writing the program, the micro is
replaced by corresponding macro expansion during execution.
Note:
The space between # and define is optional.
Macro and its expansion are separated by blanks or tabs.
Macro definition is never be terminated by a semicolon.
The use of macro makes the execution fast but takes more memory space.
The use of function slows down the execution but take less memory space.
Use of macro
The execution is fast due to the pre-execution
It reduces the program size.
The macro is useful in the place where the numbers are not to be allowed.
For example:
#include<stdio.h>
#include<conio.h>
void main()
{ Output
printf("File :%s\n", __FILE__ ); File :test.c
printf("Date :%s\n", __DATE__ ); Date :Jun 2 2012
printf("Time :%s\n", __TIME__ ); Time :03:36:24
printf("Line :%d\n", __LINE__ ); Line :8
getch();
}
Parameterized Macros
Macros with arguments must be defined using the #define directive before they can be used. The
argument list is enclosed in parentheses and must immediately follow the macro name. Spaces
are not allowed between and macro name and open parenthesis.
For example – 1:
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void)
{
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
For example – 2:
#include <stdio.h>
#include <conio.h>
#define AREA(x) (3.14*x*x)
void main ()
{
float r1 = 6.25, r2 = 2.5, a;
a = AREA (r1);
printf(“\n Area of circle is = %f”, a);
a = AREA (r2);
printf(“\n Area of circle is = %f”, a);
getch();
}
Scope: The scope of the variable (where it can be used), is determined by where it is defined. If it
is defined outside of all the blocks, it has file scope. This means, it may be accessed anywhere in
the current source code file. This is normally called a global variable and is normally defined at
the top of the source code. All other types of variables are local variables. If a variable is defined
in a block (encapsulated with {and}), its scope begins when the variable is defined and ends
when it hits the terminating. This is called block scope.
Life Time: Life time refers to the permanence of a variable – How long the variable will retain
its value in memory.
void main()
{ auto int m = 1000;
function1();
function2();
printf ("%d \n" , m);
getch();
}
void function1()
{
auto int m = 10;
printf ("%d \n" , m);
}
Output:
void function2() 10
{ 100
auto int m = 100; 1000
printf ("%d \n" , m);
}
One important feature of automatic variables is that their value cannot be changed by
whatever happens in some other function in the program. A variable local to the main
function will be normally alive throughout the whole program, although it is active only in
main(). In the case recursive functions, the nested variables are unique auto variables, a
situation similar to function nested auto variables, with identical names.
Example – 2
#include<stdio.h>
#include<conio.h>
void incre(void);
void main()
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 12
Example:
#include<stdio.h>
#include<conio.h>
void fun(void);
int a = 5 ; /* Global variable (No need to use extern
keyword) */
void main()
{
extern int b; /* external variable declaration*/
void fun();
fun();
printf(" %d " , a); /* prints 10 */
printf(" %d " , b); /* prints 20 */
getch();
}
void fun()
{ Output: 10 20
a = 10 ;
}
int b = 20;
It is possible to inform the compiler that a variable should be kept in one of the registers,
instead of keeping it in the memory. Since registers are faster than memory, keeping the
frequently accessed variables like a loop control variable in a register will increase the
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 13
Note:
Life of the static, automatic and external storage class
OR
#include<stdio.h>
#include<conio.h>
int factorial(int);
void main()
{ int num,result;
printf("Enter a number:\n");
scanf("%d",&num);
result=factorial(num);
printf("factorial of %d=%d",num,result);
getch();
}
int factorial(int n)
{
if(n==1)
return 1;
else
return(n*factorial(n-1));
}
5. Write a program to calculate the area and perimeter of a rectangle using function
#include<stdio.h>
#include<conio.h>
void area(int,int);
void perimeter(int,int);
void main()
{
int l,b;
printf("Enter length and breadth:");
scanf("%d%d",&l,&b);
area(l,b);
perimeter(l,b); Output:
getch(); Enter length and breadth:- 4
} 5
void area(int x,int y) area=20
{ perimeter=18
int area1;
area1=x*y;
printf("area=%d",area1);
}
void perimeter(int x,int y)
{
int peri;
peri=2*(x+y);
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 17
7. Write a program to swap the values of two variables using a function. (Passing by value)
#include<stdio.h>
#include<conio.h>
void swap(int,int);
void main()
{
int x,y;
printf("Enter x and y:");
scanf("%d%d",&x,&y);
printf("before calling swap\nx=%d\ny=%d",x,y);
swap(x,y);
printf("\n\nafter calling swap\nx=%d\ny=%d",x,y);
getch();
} Output:
void swap(int p,int q) Enter x and y : 8 9
{ before c alling swap
int temp; x=8
temp=p; Y=9
p=q; after calling swap
q=temp; x=8
} y=9
HOME WORK