Professional Documents
Culture Documents
CP M3 Ktunotes - in
CP M3 Ktunotes - in
CP M3 Ktunotes - in
FUNCTIONS
that are .
E S . I N
In order to make use of a function, there is a need to establish three elements
KTU NOT
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:
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
. I N
Function definition, also known as function implementation includes the
E S
NOT
following elements;
KTU
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.
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
statement.
E S . I N
program. If a function does not return any value, omit the return
KTU NOT
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:
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:
KTU
c= sum(a,b); NOT
printf(“sum of two numbers = %d”, c);
/* function call */
}
/* function definition*/
int ( int x, int y) /* function header */
{ /*
int result;
result = x + y ; function body
return(result);
} */
Parameter Passing Methods
The technique used to pass data from one function to another is known as
parameter-passing. In C parameter passing can be done in two ways:
E S . I N
NOT
A function may belong to one of the following categories:
KTU
1. Functions with no arguments and no return values or empty parameter list.
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.
Output
E S . I N
NOT
Function text1() takes no arguments
KTU
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
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
S . I N
/*To find sum of three numbers using functions having arguments with return values*/
E
NOT
#include <stdio.h>
KTU
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
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)
{
E S . I N
NOT
int f;
KTU
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));
}
STORAGE CLASSES
Automatic variables
External variables
Static variables
Register variables
Automatic Variables
S . I N
Automatic variables are declared inside a function in which they are to be utilized.
E
NOT
They are created when the function is called and destroyed automatically when the function is
KTU
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
--------
--------
}
Function2()
{
printf(“%d”,count);
E S
/* print count=50*/
. I N
---------
----------
} KTU NOT
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
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;
E S . I N
NOT
printf (“%d”, x);
Output
KTU
x=1 x=2 x=3
12
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.
E S . I N
KTU NOT
The C language contains a number of library functions that perform
various tasks. Those are
<ctype.h> character testing and conversion functions
<math.h> mathematical functions
<stdio.h> standard I/O library functions
<stdlib.h> Utility functions such as string conversion routines, memory allocation
routines.
<string.h> String manipulation functions
<time.h> Time manipulation functions.
THE C PREPROCESSOR
13
E S . I N
NOT
Macro Substitution
KTU
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
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
E S . I N
KTU
#define square(x) ((x)*(x))
#define cube(x) (square(x)*(x)) NOT
Macros can also be used as parameters of other macros.
#define M 7
#define N 6
#define MAX (M, N) (((M)> (N))? (M): (N))
Undefining a Macro
A defined macro can be undefined, using the statement
#undef name
This is used to restrict the definition only to a particular part of the program.
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
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
E S . I N
NOT
type variable-name [50];
KTU
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
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.
E S . I N
NOT
{
KTU
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array\n”);
for I=0;I < n;I++)
scanf(“%d”,&a[I]);
for(I=0;I < n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the array\n”,count_neg);
printf(“There are %d positive numbers in the array\n”,count_pos);
}
17
main( )
{
int limit; /* variable declaration */
float avg; /* variable declaration */
float list[25]; /* variable declaration */
……………
…………….
avg=average(list,limit);
E S . I N
NOT
……………
KTU
}
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
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*/
E S . I N
NOT
Application Of Arrays
Multidimensional arrays are commonly used in numerical algorithms (mainly
KTU
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
#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);
E S . I N
NOT
avg=average(sum);
printf(“Average=%f”,avg);
}
KTU
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
#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++)
E S . I N
NOT
scanf(“%d”,&b[i]);
KTU
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
E S . I N
NOT
int a[10][10],n;
printf(“enter the limit of raw and column”);
KTU
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