CP Module 3 PDF
CP Module 3 PDF
FUNCTIONS
1. Function declaration.
2. Function definition.
3. Function call.
Function Declaration
All functions in a c program must be declared, before they are invoked. A
function declaration (also known as function prototype) consists of four parts.
In function declaration:
1
If the function has no formal parameters, the list is written as „(void)‟.
The return type is optional, when the function returns int type data.
The return type must be void if no value is returned.
Example: int addition (int a , int b) ;
int – function-type
addition – function-name
When we place the declaration above all the functions, the prototype is referred to
as a global prototype. Such declarations are available for all the functions in the program.
When we place it in a function definition (in the local declaration section), the prototype is
called a local prototype. Such declarations are primarily used by the functions containing
them.
Function Definition
Function definition, also known as function implementation includes the
following elements;
Function name.
Function type.
List of parameters.
Local variable declaration.
Function statements; and
A return statement.
These elements are grouped into two parts, namely, function header and function body.
2
In which function-type function-name (parameter list) is known as the
function header, and the statements within the opening and closing braces constitute the
function body, which is a compound statement.
function type :- specifies the type of value (data type) that is returned by the function. If
the return type is not explicitly specified, C will assume that it is an
integer type. If the function is not returning anything then specify the
return type as void.
function name :- the function name is any valid C identifier.
List of parameters :-the parameters are called formal parameters, because they represent the
names of data items that are transferred into the function from the
calling portion of the program. They are also known as arguments or
formal arguments. The identifiers used as formal arguments are ‟local‟
in the sense that they are not recognized outside of the function. Hence,
the names of the formal parameters need not be the same as the names of
the actual arguments in the calling portion of the program.
function body :- the function body contains the declarations and statements necessary for
performing the required task. It should include one or more return
statements, in order to return a value to the calling portion of the
program. If a function does not return any value, omit the return
statement.
A function may or may not send back any value to the calling function. If
it does, it is done through the return statement. While it is possible to pass to the called function
any number of values, the called function can only return one value per call, at the most. The
return statement can take one of the following forms:
return; /* does not return any value, the control is immediately passed back to the calling
function */
Or
return (expression); /* returns the value of the expression*/
Function Call
A function can be called by simply using the function name followed by a
list of parameters (or arguments), if any, enclosed in parentheses and separated by commas. If
the function call does not require any arguments, an empty pair of parentheses must follow the
name of the function. The function call may be a part of a simple expression (such as an
assignment statement), or it may be one of the operands within a more complex expression. The
arguments appearing in the function call are referred to as actual parameters.
The general format of function call is:
3
If the function returns a value, the function access is often written as an
assignment statement; .i.e.
variable = function name (actual parameters);
On the other hand, if the function does not return anything, the function call
appears by itself; .i.e.
function name ( actual parameters );
There may be several different calls to the same function from various
places within a program. The actual arguments may differ from one function call to another.
Within each function call, however, the actual arguments must correspond to the formal
arguments in the function definition; i.e., the number of actual arguments must be the same as
the number of formal arguments, and each actual argument must be of the same data type as its
corresponding formal argument.
Example:
4
In pass by value, values of actual parameters are copied to the
variables in the parameter list of the called function (sending value of arguments onto the
function). That is the called function is given the values of its arguments in temporary variables
rather than the originals, therefore any change maid in the variable value will not affect the
original variable.
5
int a,b;
printf(“Enter the values:”);
a=10;
b=20;
swap(&a,&b);
printf(“a=%d b=%d”,a,b);
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“x=%d y=%d”,*x,*y);
}
output
x=20 y=10
a=10 b=20
Categories of Functions
A function may belong to one of the following categories:
An empty parameter list refers to the list with no arguments or parameters. A function
can be defined with empty parameter list.In C an empty parameter list specified by writing
either void or nothing at all in the parenthesis of function definition.A simple format of
declaring empty parameter list is given below:
void display();
or
void display(void);
In above declaration, display is a function that does not take any arguments and does
not return a value. The following example demonstrates both C ways of declaring and using
functions that do not take arguments.
6
Example
/*To demonstrate the way of declaring and using functions with no arguments*/
#include<stdio.h>
void text1(); // Function with no argument
void text2(void); // Function with no arguments(void)
main()
{
text1();
text2();
}
void text1()
{
Printf(“Function text1() takes no arguments\n”);
}
void text2()
{
Printf(“Function text2() takes no arguments\n”);
}
Output
Function text1() takes no arguments
Function text2() also does not takes no arguments
In above given program,text1 and text2 are the functions with no arguments and
the type of functions is also void so the function does not return any value. The empty
parameter list in function text2 is specified by writing void in the parenthesis. But it‟s meaning
ia same as that of blank space in text1.
Arguments But No Return Values
7
void largest(int a,int b)
{
if(a>b)
printf(“Largest element is :%d”,a);
else
printf(“Largest element is :%d”,b);
}
Output
In the above program we could make the calling function to read data from the
terminal and pay ii on to the called function. But the function does not return any value.
Arguments With Return Values
/*To find sum of three numbers using functions having arguments with return values*/
#include <stdio.h>
main()
{
int a,b,c,sum;
int add(int,int,int);
printf(“Enter three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
sum=add(a,b,c);
printf(“Sum=%d”,sum);
}
add(int x,int y,int z)
{
int s;
s=x+y+z;
return(s);
}
Output
8
25
62
13
Sum=100
In above given program, the function add receives data from the calling function (three
values a,b,c) through arguments and function, add return a value to sum variable.
Recursion
Recursion is the mechanism by which a function calls itself; it is a very strong tool in
the hands of programmers. By using recursion complex logic can easily be written. The use of
recursion improves the readability of the program, but the overhead of processor is increased.
Recursive functions can be effectively used to solve problems where solution is
expressed in terms of successively applying the same solution to subsets of the problem. When
we write recursive functions, we must have an if statement somewhere to force the function to
return without the recursive call being executed. Otherwise, the function will never return.
Example
/* recursive function for factorial*/
int fact(int x)
{
int f;
If(x<=1)
return (1);
else
f=x*fact(x-1);
return (f);
}
/*recursive function for fibonnaci series*/
int fibonnaci (int x)
{
if(x<=2) return 1;
return fibonnaci(x-1)+fibonnaci(x-2);
}
main()
{
printf("\n fact(10) : %d",fact(10));
printf("\n fibonnaci(10) : %d",fibonnaci(10));
}
9
PROGRAM STRUCTUERS
STORAGE CLASSES
Automatic variables
External variables
Static variables
Register variables
Automatic Variables
Automatic variables are declared inside a function in which they are to be utilized.
They are created when the function is called and destroyed automatically when the function is
exited, hence the name automatic. Automatic variables are therefore private (or local) to the
function in which they are declared. Because of this property, automatic variables are also
referred to as local or internal variables. The general form of the variable declaration statement
that includes the storage specifier is given as follows:
< Storage class specifier > < data type > < variable name > ;
Example:
External variables
Variables that are both alive and active throughout the entire program are known as
external variables. They are also known as global variables. Unlike local variables, global
variables can be accessed by any function in the program. External variables are declared
outside a function.
10
Example:
--------
--------
}
Function2()
{
printf(“%d”,count); /* print count=50*/
---------
----------
}
The variables number and length are available for use in all the
three functions. In case of a local variable and a global variable have the same name, the
local variable will have precedence over the global one in the function where it is
declared.
Static variables
The value of static variables persists until the end of the program. A
variable can be declared static using the keyword static.
static int x;
static float y;
A static variable may be either an internal type or an external type depending on the
place of declaration.
Internal static variables are those which are declared inside a function.
The scopes of these variables extend up to the end of the function in which they are
defined. Therefore internal static variables are similar to auto variables, except that they
11
remain in existence (alive) throughout the remainder of the program. Therefore, internal
static variables can be used to retain values between function calls.
An external static variable is declared outside of all functions and is
available to all the functions in that program. The difference between a static external
variable and a simple external variable is that the static external variable is available
only within the file where it is defined while the simple external variable can be
accessed by other files.
Example:
main ()
{
int i;
for (i=1; i<=3;i++)
Function1 ();
}
Function1 ()
{
static int x=0; /* take the value of x=0*/
x=x+1;
printf (“%d”, x);
Output
x=1 x=2 x=3
12
register int a,b,c;
LIBRARY FUNCTIONS
C functions can be classified into two categories, namely, library
functions and user-defined functions. Some functions are written by users, and many
others are stored in the C library. The only difference is that the source code (definition)
for a library function does not appear in your program. The prototype for the library
function is provided to your program using the #include compiler directive. A user
defined function has to be developed by the user at the time of writing a program. To use
a library function, need to include the proper header file and know the name of the
function that wish to use.
THE C PREPROCESSOR
13
#include "filename"
Or
#include <filename>
is replaced by the contents of the file filename. If the filename is quoted, searching for
the file typically begins where the source program was found; if it is not found there, or
if the name is enclosed in < and >, searching follows an implementation-defined rule to
find the file. (i.e., When the filename is included within the double quotation marks, the
search for the file is made first in the current directory and then in the standard
directories. In the second case, the file is searched only in the standard directories.)
An included file may itself contain #include lines.
There are often several #include lines at the beginning of a source
file, to include common #define statements and extern declarations, or to access the
function prototype declarations for library functions from headers like <stdio.h>.
(Strictly speaking, these need not be files; the details of how headers are accessed are
implementation-dependent.)
#include is the preferred way to tie the declarations together for a
large program. It guarantees that all the source files will be supplied with the same
definitions and variable declarations, and thus eliminates a particularly nasty kind of
bug. Naturally, when an included file is changed, all files that depend on it must be
recompiled.
Macro Substitution
A definition has the form
It calls for a macro substitution of the simplest kind - subsequent occurrences of the
token name will be replaced by the replacement text. The name in a #define has the
same form as a variable name; the replacement text is arbitrary. Normally the
replacement text is the rest of the line, but a long definition may be continued onto
several lines by placing a \ at the end of each line to be continued. The scope of a name
defined with #define is from its point of definition to the end of the source file being
compiled. A definition may use previous definitions. Substitutions are made only for
tokens, and do not take place within quoted strings. For example, if YES is a defined
name, there would be no substitution in printf("YES") or in YESMAN.
Any name may be defined with any replacement text. For example
#define forever for (;;) /* infinite loop */
Defines a new word, forever, for an infinite loop.
14
It is also possible to define macros with arguments, so the
replacement text can be different for different calls of the macro. As an example, define
a macro called max:
Although it looks like a function call, a use of max expands into in-line code. Each
occurrence of a formal parameter (here A or B) will be replaced by the corresponding
actual argument. Thus the line
x = max (p+q, r+s);
will be replaced by the line
x = ((p+q) > (r+s) ? (p+q) : (r+s));
So long as the arguments are treated consistently, this macro will serve for any data
type; there is no need for different kinds of max for different data types, as there would
be with functions.
Nesting Of Macros
We can use macros in the definition of another macro. That is, macro definitions
may nested.
Example
ARRAYS
Defining and Processing Arrays
.
Definition
An array in C Programming Language can be defined as number of
memory locations, each of which can store the same data type and which can be references
through the same variable name. An array is a fixed-size sequenced collection of elements
15
of the same data type. It is simply a grouping of like-type data. An array can be used to
represent a list of numbers, or a list of names
An array is a collective name given to a group of similar quantities. These
similar quantities could be percentage marks of 100 students, number of chairs in home, or
salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar
elements. These similar elements could be all integers or all floats or all characters etc.
Usually, the array of characters is called a “string”, where as an array of integers or floats
are called simply an array. Since an array provides a convenient structure for representing
data, it is classified as one of the data structures in C.
All elements of any given array must be of the same type i.e we can‟t have
an array of 10 numbers, of which 5 are ints and 5 are floats.
Declaration of an Array
The type specifies the type of the elements that will be contained in
the array, such as int float or char and the size indicates the maximum number of
elements that can be stored inside the array . In C Language, arrays starts at position 0.
The elements of the array occupy adjacent locations in memory. C Language treats the
name of the array as if it were a pointer to the first element This is important in
understanding how to do arithmetic with arrays. Any item in the array can be accessed
through its index, and it can be accesed any where from with in the program
Initialization of arrays:
We can initialize the elements in the array in the same way as the ordinary variables
when they are declared. The general form of initialization off arrays is:
The values in the list care separated by commas, for example the statement
16
Will declare the array size as an array of size 3 and will assign zero to
each element if the number of values in the list is less than the number of elements, then
only that many elements are initialized. The remaining elements will be set to zero
automatically.
In the declaration of an array the size may be omitted, in such cases the compiler
allocates enough space for all initialized elements. For example the statement
int counter[]={1,1,1,1};
Will declare the array to contain four elements with initial values 1. this approach works
fine as long as we initialize every element in the array.
17
An entire array can be passed to a function as an argument. To pass an array to
a function, the array name must appear by itself, without brackets or subscripts, as an
actual argument within the function call.
When an array is passed to a function, however, the values of the array elements
are not passed to the function. Rather, the array name is interpreted as the address of the
first array element. This address is assigned to the corresponding formal argument when
the function is called. The formal argument therefore becomes a pointer to the first array
element. Arguments that are passed in this manner are said to be passed by reference
rather than by value.
For example:
float average(float arr[ ] ,int x); /* function prototype*/
main( )
{
int limit; /* variable declaration */
float avg; /* variable declaration */
float list[25]; /* variable declaration */
……………
…………….
avg=average(list,limit);
……………
}
float average(float arr[ ],int x) /* function definition */
{
…………….
}
average(list,limit);
will pass the whole array „list‟ to the called function. The called function expecting this
call must be appropriately defined.
The function header might look like :
float average(float arr[ ],int x)
The function „average‟ is defined to take two arguments, the array name and the size of
the array to specify the number of elements in the array.
18
of square brackets. Elements are stored by rows, so the right most subscript, or column,
varies as elements are accessed in storage order.
Multidimensional Arrays:
The general form of a multi-dimensional array is
type array_name [s1][s2][s3]…..[sn]; where Si is the size of the ith dimension.
For ex:
int table[3][5][2]; /* is a three-dimensional array can be represented as a series of two-
dimensional arrays*/
Application Of Arrays
Multidimensional arrays are commonly used in numerical algorithms (mainly
from applied linear algebra) to store matrices.
Example programs.
Functions
#include<stdio.h>
main()
{
int a,b;
void addition(int, int);
printf(“enter two numbers”);
scanf(“%d %d:,&a,&b);
addition(a,b);
}
19
void addition(int x, int y)
{
int sum=0;
sum=x+y;
printf(“ sum = %d”,sum);
}
#include<stdio.h>
main()
{
int a,b;
float sum=0,avg=0;
float average(float);
printf(“enter two numbers”);
scanf(“%d %d”,&a,&b);
sum=a+b;
printf(“sum=%f”,sum);
avg=average(sum);
printf(“Average=%f”,avg);
}
float addition(float a)
{
float result;
result=a/2;
return result;
}
Arrays
1) Write a C program to display a list of numbers
Program
#include<stdio.h>
main()
{
int a[10],n;
printf(“enter the limit”);
scanf(“%d”,&n);
printf(“enter %d numbers from keyboard”,n);
for(i=0; i<n; i++)
20
scanf(“%d”,&a[i]);
for(i=0; i<n; i++)
printf(“%d”,a[i]);
}
#include<stdio.h>
main()
{
int a[10],b[10],c[10],n;
printf(“enter the limit”);
scanf(“%d”,&n);
printf(“enter %d numbers in to first array”,n);
for(i=0; i<n; i++)
scanf(“%d”,&a[i]);
printf(“enter %d numbers in to second array”,n);
for(i=0; i<n; i++)
scanf(“%d”,&b[i]);
for(i=0; i<n; i++)
c[i]=a[i]+b[i];
printf(“ The sum is”);
for(i=0; i<n; i++)
printf(“%d”,c[i]);
}
Passing arrays to functions
Program
#include<stdio.h>
main()
{
int a[10],n;
void mult(int [],int);
printf(“enter the limit”);
scanf(“%d”,&n);
21
printf(“enter %d numbers in to array”,n);
for(i=0; i<n; i++)
scanf(“%d”,&a[i]);
mult(a,n);
}
void mult(int p[10],int x)
{
int t;
printf(“enter the multiplier”);
scanf(“%d”,&t);
for(i=0; i<x; i++)
p[i]=p[i]*t;
for(i=0; i<n; i++)
printf(“%d”,c[i]);
}
4) Write a C program to display a matrix
Program
#include<stdio.h>
main()
{
int a[10][10],n;
printf(“enter the limit of raw and column”);
scanf(“%d %d”,&n,&m);
printf(“enter %d X %d matrix”,n,m);
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf(“%d”,&a[i][j]);
printf(“ The matrix is”);
for(i=0; i<n; i++)
for(j=0; j<n; j++)
printf(“%d”,a[i][j]); }
22