You are on page 1of 19

CHAPTER - 6

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

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 1

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


6.2 Defining a function (Function Definition)
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.

Syntax:
return_type function_name(parameter list )
{
body of the function
}

A function definition in C programming language consists of a function header and a function


body. Here are all the parts of a function:
 Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define what
the function does.

Local and Global declaration of function


 If we define the data type of variable or constant inside the function, it is called
function declaration or local declaration of 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.

The advantage of function prototyping is that it enables a compiler to compare each


use of function with the prototype to determine whether the function is invoked
properly or not. The number and types of arguments can be easily compared and any
wrong number or type of the argument is reported. Therefore, the function
prototyping makes C straightway point to the error.

The example will be shown in next coming program.

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 2

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Local Variables or automatic variable
The variables declared inside any function are local to that function. It can be accessed only
within that function. Memory for the local variables is allocated only when the function is
invoked and de-allocated when the control moves out of the function.

Global Variables or External Variable


The variables that are common to all the functions are declared outside the functions. If it is
declared in the Global declaration section, it is used by all the functions in the program. Memory
for the global variables is allocated, when the program gets executed and de allocated only at the
end of program execution. The return statement is used to transfer the control back to the calling
program. A function may or may not return a value to the calling function. A function may
receive any number of values from the called function. If it returns a value, it is achieved by the
return statement. There can be multiple return statements, each containing different expression.
 If there is no return statement, the closing braces (}) in the function body acts as a return
statement.

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();
}

void printline (char ch)


{
int i;
for (i=0; i<=20; i++)
printf ("%c", ch);
}

void calsum(int x, int y) // x and y are formal arguments where x = a and y = b


{
int sum;
sum = x+y;
printf ("\nThe sum is %d\n", sum);
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 3

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


6.3 Declaring the type of the function (Function prototype)
The function may return varying type of value to the calling portion of the program. Any of the
data type such as int, float, char etc. can be in the function declaration. If a function is not
supposed to return value, it can be declared as type void. Function declaration of the function
tells the program about the type of value returned by the function and the number and type of
arguments.

void (or No return value) Non-void (With return value)


Argument passed Argument passed
Example: void myfunction ( Example: float myfunction (
float a, char b, int c) float a, char b, int c)
No argument passed No argument passed
Example: void myfunction (void) Example: int myfunction (void)

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; }
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 4

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


6.4 Return Statements
The return statement allows the following behaviors:
1. On executing the return, it immediately transfers the control back to the calling function.

For example: WAP to convert the ASCII value of given character


#include<stdio.h>
#include<conio.h>
int function(int n);
void main()
{
int value, n;
value = function(n);
printf("%d", value);
getch();
}
function (int n)
{
char ch;
printf ("Enter any alphabet");
scanf ("%c", &ch);
return (ch);
}

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.

7. The return statement may or may not include an expression.

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 5

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


For example:
#include <stdio.h>
#include <conio.h>
int sqr(int);
int sum(int,int);
int sumsqr(int,int);

int sqr(z)
int z;
{
return (z*z);
}

int sum(int x, int y)


{
return (x+y);
}
/*returns sum of squares of two arguments*/
int sumsqr(int j, int k)
{
return (sum(sqr(j),sqr(k)));
}
void main()
{
int num1,num2;
clrscr();
printf("Enter two numbers:");
scanf ("%d %d",&num1,&num2);
printf ("The square of %d is %d",num1,sqr(num1));
printf("\nThe square of %d is %d",num2,sqr(num2));
printf("\nSum of squares is %d",sumsqr(num1,num2));
getch();
}

6.5 Passing arguments to a Function


There are two approaches to pass the information to a function via arguments. They are: Call by
Value and Call by Reference.

A. Argument (or parameter) pass by value


The process of passing the value of variable in function is called argument call by value.
Arguments are usually passed by value in C function calls. The values of the actual arguments
are copied in to the respective formal arguments. Actual and formal arguments refer to the
different memory locations and the value of actual argument is copied into the formal
argument. So, any changes made to the formal argument are not reflected in their
corresponding actual arguments. The value of the actual argument will remain same.
For example: Program that illustrates call by value mechanism
#include<stdio.h>
#include<conio.h>
void swap(int, int);
void main()
{
int a, b;
a=10;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 6

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


b=20;
swap(a, b); //Argument pass by value
//passing the values of a and b to c and d of swap function
printf("\n%d %d", a, b); // prints 10 20
getch();
}
void swap(int c, int d)
//Function used to swap the values of variables c and d
{
int temp;
temp = c;
c = d;
d = temp;
printf("%d %d", c, d);
}

B. Argument pass by reference


In this approach, the addresses of actual arguments are passed to the function call and the
formal arguments will receive the address. The actual and formal arguments refer to the same
memory location. So, changes in the formal arguments are reflected in actual arguments.
Actual arguments are address of the ordinary variable, pointer variable or array name. Formal
arguments should be a pointer variable or array. This approach is of practical importance while
passing arrays to functions and returning back more than one value to the calling function.
Passing arrays to functions is call by reference by default.

Example: Program that illustrates call by reference mechanism


#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y);
void main()
{
int a, b;
a=10;
b=20;
swap(&a, &b); // Argument pass by reference
//passing the addresses of a and b to c and d of swap function
printf("\n%d %d", a, b); // prints 20 10
getch();
}
void swap(int *c, int *d) // reference is made
{
int temp;
temp = *c;
*c = *d;
*d = temp;
printf("%d %d", c, d);
}

Q. Program to show the function call process.


#include<stdio.h>
#include<conio.h>
void nepal();
void kathmandu(void);
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 7

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


void india(void);
void lalitpur();
void delhi(void);
void main()
{ clrscr();
printf("I'm inside main function\n");
nepal(); //Function Call
india();
printf("Finally, I'm back inside main function\n");
printf("bye\n");
getch();
}
void nepal()
{ printf("I'm inside nepal\n");
kathmandu();
printf("Now, I'm going to leave Nepal & go to India\n");
}
void kathmandu(void)
{ printf("I'm inside Kathmandu\n");
lalitpur();
}
void india(void) //Function Defination
{ printf("I'm inside India\n");
delhi();
printf("Leaving India going to main function\n");
}
void delhi(void)
{ printf("I'm inside delhi\n");
}

void lalitpur()
{ printf("I'm inside lalitpur\n");
}

6.6 C Preprocessor directives


The C Preprocessor is not part of the compiler, but is a separate step in the compilation process.
In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to
do required pre-processing before actual compilation. All preprocessor commands begin with a
pound symbol (#). Following section lists down all important preprocessor directives:

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

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 8

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Examples Description
#define VAL 20 Replace instances of VAL with 20. Use #define for constants
to increase readability.
#include <stdio.h> First line: Get stdio.h from System Libraries
#include "myheader.h" The next line: Get myheader.h from the local directory
#undef FILE_SIZE This tells the CPP to undefine existing FILE_SIZE and
#define FILE_SIZE 42 define it as 42. Note: CPP = Compiler Pre-Preocessor
#ifndef MESSAGE This tells the CPP to define MESSAGE only if MESSAGE
#define MESSAGE "You wish!" isn't already defined.
#endif
#ifdef DEBUG This tells the CPP to do the process the statements enclosed if
/* Debugging statements here */ DEBUG is defined.
#endif

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: WAP to calculate the area of a circle using macro.


#include<stdio.h>
#include<conio.h> Here,
#define PI 3.14159  # = Pre-processor
 define = Macro representation
float area(float radius)  PI = Macro template or Macro
{  3.14159 = Macro expansion
float area;
area=PI*radius*radius;
return area;
}
void main()
{
float r,a;
clrscr();
printf("Enter the radius of a circle: ");
scanf("%f",&r);
a=area(r);
printf("The area of a circle is %f",a);
getch();
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 9

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Predefined Macros
C defines a number of macros that should not be directly modified.
Macro Description
__DATE__ The current date as a character literal in "MMM DD YYYY" format
__TIME__ The current time as a character literal in "HH:MM:SS" format
__FILE__ This contains the current filename as a string literal.
__LINE__ This contains the current line number as a decimal constant.

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;
}

Output: Max between 20 and 10 is 20

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();
}

Output: Area of circle is = 122.65625


Area of circle is = 19.625

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 10

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


6.7 Storage Classes
Variables in C can be characterized by their data type and storage classes. Data type refers to the
type of information represented by a variable and storage classes define its life time and scope.
The storage-class can be:
Storage class Keywords
Automatic storage class auto
External storage class extern
Static storage class static
Register storage class register

The storage class tells four things for a variable:


1. Storage: Where the variable would be storage i.e. memory or CPU registers.
2. Default initial value: What will be the initial value of the variable, if the initial value is
not specifically assigned.
3. Scope: What is the scope of the variable i.e. in which function the value of the variable is
available.
4. Life time: What is the life of the variable i.e. how long would the variable value exists.

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.

General Form: storage-class-specifier type-specifier variable-name;

A. Automatic variables (Auto storage class)


Storage location Memory
Default initial value Unpredictable (garbage value)
Scope Local to the function in which the variable is defined
Life time Till the control remain in the function in which it is defined
Note: If no storage class is specified, by default it is an auto variable.

Example – 1: For default initial value


#include<stdio.h>
#include<conio.h>
void calsum(void);
void main()
{ auto int a ;
printf ("%d" , a);
calsum ();
getch();
} Output:
void calsum() Any garbage value
{ printf ("\n"); 0
auto int a =0;
printf ("%d" , a);
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 11

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Example – 2: For scope of variable
#include<stdio.h>
#include<conio.h>
void function1(void);
void function2(void);

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.

B. Static variables (static storage class)


Storage location Memory
Default initial value Zero
Scope Local to the function in which the variable is defined
Life time Value of the variable persists between different function calls

Example – 1: For default initial value


#include<stdio.h>
#include<conio.h>
void main()
{ static int a ;
printf ("%d" , a); Output: 0
getch();
}

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

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


{
int i;
for (i=1;i<=5;i++)
incre();
getch(); Output:
} x = 1
void incre() x = 2
{ x = 3
static int x = 0; x = 4
x = 5
x = x +1;
printf(" x = %d\n",x);
}

C. External variables (extern storage class)


Storage location Memory
Default initial value Zero
Scope Global
Life time As long as the programs execution does not come to end.

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;

D. Register variables (register storage class)


Storage location CPU registers
Default initial value Garbage value
Scope Local to the function in which the variable is defined
Life time Till the control remain in the function in which it is defined

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

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


execution speed. Since the registers are less in numbers, careful selection must be made for
their use. If the declaration of register variable exceeds the availability, they will be
automatically converted into non register variables (automatic variable). Only the integer
values are declared in register storage class because in micro-computer, there is 32 byte space
so the float, long double, and double values are not accepted.

Example – 1: For default initial value


#include<stdio.h>
#include<conio.h>
void main() Output: Any garbage value
{ static int a ;
printf ("%d" , a);
getch();
}

Note:
Life of the static, automatic and external storage class

Automatic Static External


#include<stdio.h> #include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h> #include<conio.h>
void increment void increment Voidincrement (void);
(void); (void); void decrement (void);
void main() void main() int i;
{ { void main()
increment (); increment (); {
increment (); increment (); printf ("\n%d", i);
increment (); increment (); increment ();
getch(); getch(); increment ();
} } decrement ();
decrement ();
void increment () void increment () getch();
{ { }
auto int i =1; static int i =1;
printf ("%d\n" , i); printf ("%d\n" , i); void increment ()
i = i+1; i = i+1; {
} } i = i+1;
printf ("\n%d ", i);
}
Output:
Output: 1
void decrement ()
1 2
{ i = i-1;
1 3
printf ("\n%d ", i);
1 }
Output:
0
1
2
1
0

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 14

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


6.8 Recursion
In C, it is possible for the functions to call themselves. A function is called 'recursive' if a
statement within the body of a function calls the same function. Sometimes called 'circular
definition', recursion is thus the process of defining something in terms of itself.

Example: WAP to demonstrate factorial function using recursion.


#include<stdio.h>
#include<conio.h>
long int factorial(long int n);
void main()
{
long int answer,n;
clrscr();
printf("Enter the number: ");
scanf("%ld",&n);
answer=factorial(n);
printf("The factorial of %ld! is %ld",n,answer);
getch();
}
long int factorial(long int n)
{
long int fact=1;
if(n==0)
return fact;
else if(n>0)
{
for(int i=1;i<=n;i++)
fact*=i;
return fact;
}
else
return 0;
}

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));
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 15

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


LAB SECTION

1. Program to illustrate function with no arguments and no return values.


#include<stdio.h>
#include<conio.h>
void add();
void main()
{
add();
getch();
}
void add() Output:
{ Enter two numbers:
int a,b,sum; 4
printf("Enter two numbers:"); 5
scanf("%d%d",&a,&b); Sum=9
sum=(a+b);
printf("sum=%d",sum);
}

2. Program to illustrate function with arguments and no return values.


#include<stdio.h>
#include<conio.h>
void add(int,int);
void main()
{
int a,b;
printf("Enter values of a and b:");
scanf("%d%d",&a,&b);
add(a,b); Output:
getch(); Enter values of a and b:4
} 5
void add(int p,int q) Sum=9
{
int sum;
sum=p+q;
printf("\nsum=%d",sum);
}

3. Program to illustrate function with arguments and return values.


#include<stdio.h>
#include<conio.h>
int add(int,int);
void main()
{
int a,b,result;
printf("Enter the values of two numbers:");
scanf("%d%d",&a,&b);
result=add(a,b);
printf("\nThe sum=%d",result);
getch();
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 16

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


int add(int p,int q)
{
int sum; Output:
sum=p+q; Enter the values of two numbers:4
return sum; 5
} The sum=9

4. Program to illustrate function with no arguments and return values.*/


#include<stdio.h>
#include<conio.h>
int add();
void main()
{
int result;
result=add();
printf("\nThe sum=%d",result);
getch();
}
int add()
{
int a,b,sum;
printf("Enter two numbers:");
scanf("%d%d",&a,&b);
sum=a+b; Output:
return sum; Enter two numbers: 4
} 5
The sum = 9

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

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


printf("\nperimeter=%d",peri);
}

6. Write a program to generate the Fibonacci series using function.


#include<stdio.h>
#include<conio.h>
void fibo(int,int,int);
void main()
{ int a,b,num;
printf("Enter first number");
scanf("%d",&a);
printf("Enter second number");
scanf("%d",&b);
printf("Enter number of terms of series.");
scanf("%d",&num);
fibo(a,b,num);
getch();
}
void fibo(int x,int y,int n)
{
int sum=0,i; Output:
printf("%d%d",x,y); Enter first number 0
for(i=2;i<n;i++); Enter second number 1
{ Enter number of terms of series. 2
sum=x+y; 011
printf("%d",sum);
x=y;
y=sum;
}
}

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

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 18

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


8. Write a program to swap the values of two variables using a function. Pass the arguments
to function by reference. (Passing by reference)
#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=9
}
y=8

HOME WORK

 Write a program to calculate the value as base and power is supplied


 Write a program to generate the series as follows
1 2 3 4
    ....
1! 2! 3! 4!

 Write a program to generate the following series


12 123 123 4
1    .....
2! 3! 4!
 Write a program to find the cube value of a give number using function which returns the
value
 Write a program to generate the exponential series and get their sum.
 Write a program to generate the series
x1 x 2 x4 x8 x 16 x 32
1      +………
2! 3! 4! 5! 6! 7!

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 19

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)

You might also like