Professional Documents
Culture Documents
FUNCTIONS
INTRODUCTION:-
The programs written in C language are highly dependent on functions.
The c program is nothing but a combination of one or more function. We have primarily
limited to the 3 function, namely, main, printf and scanf. Every C program start with user
defined function main(). Each time when a new program is started, main() function must be
defined. The main() calls another function to share the work.
‘C’ language supports two types of functions
1) Library function -----> printf(), scanf()
2) user defined function -----> main()
2) User-defined functions:-
The user defined function has to be developed by the user at the time of
writing a program. The functions defined by the user according to their requirements are
called as user-defined functions. The user can modify the function according to the
requirement. The user certainly understands the internal working of the function. The user
has full scope to implement their own ideas in the function.
Ex:- main()
Here the user knows the internal working of the function, as it source code is visible.
Definition:-
A function is a self-contained or a sub-program of one or more statements that
performs a special task when called. A function is a block of statement that performs some
kind of task.
Advantages:-
1) It facilitates top-down modular programming the high level logic of the overall
problem is solved. First while the details of each lower –level function are addressed
later.
3
It is therefore not a surprise to note that there exist some similarities between
functions and variables in ‘c’.
1) Both functions names and variable names are considered identifiers and therefore they
must adhere to the rules for identifiers.
2) Like variables, functions have types associated with them.
3) Like variables, function names and their types must be declared and defined before they
are used in program.
In order to make use of a user-defined function, we need to establish 3 elements that are
related to functions.
1. Function declaration
2. Function call
3. Function definition
Structure of a function:-
void message(); /*function prototype declaration*/
void main()
{
function_name (parameter_list 1); /* function calling*/
/*function defition */
return_value_type function (parameter_list2)
// ex:- int message ( int x,int y,int z )
{ Formal arguments
stmt n ;
return (expression);
}
1) Function definition :- (function implementation)
A function definition also known as function implementation. This includes the following
elements.
1) function_name
2) function_type function header
3) parameters_list
4) local variable declarations
5) function statements function body
6) return statement
a) Function header:-
The function header consists of 3 parts:
i) function_type(also known as return type)
ii) function_name
iii) formal_parameter list.
Note:-semicolon is not used at the end of the function header.
b) Function Body:-
The function body contains the declaration and statements necessary for performing the
required task. The body enclosed in braces. It contains 3 parts.
1) Local declarations that specify the variables needed by the function.
2) Function statements that perform the task of the function.
3) A return statement that returns the value evaluated by the function.
(a) float mul(float x,float y)
6
{
float result; // local variable
result=x*y; //computes the products
return(result); //return the result
Note:-
1) When a function reaches its return statement, the control is transferred back to the
calling program. In the absence of a return statement, the closing brace acts as a void
return.
2) A local variable is a variable that is defined inside a function and used without having
any role in the communication between functions.
2) Function call:-
A function can be called by simply using the function name followed by a list of actual
parameters (or arguments)
main( )
{
int y;
y=mul(10,5); /*function call*/
printf (“%d\n”,y);
}
7
When the compiler encounters a function call, the control is transferred to the function
mul( ). This function is then executed line as described and a value is returned when a return
statement is encountered. This value is assigned to y.
Ex:- main( )
{
int y;
y=mul(10,5);
}
int mul(int x, int y)
{
int p;
p=x*y;
return(P);
}
The function call sends two integer values 10 and 5 to the function.
There are many different ways to call the function.
mul(10,5) mul(m+5,10)
mul(m,5) mul(10,mul(m,n))
mul(10,n) mul(expr1,expr2)
The sixth call uses its own call as its one of the parameters.
Actual Parameter:-
The parameters that are passed in function call are called actual parameters. These
parameters are defined in the calling function.
Actual parameters can be variables, constants or expressions.
Formal parameters can be only variables but not expressions or constants.
Note:-
1) If the actual parameters are greater than the formal parameters, the extra actual
arguments will be discarded.
2) On the other hand, if actual are less than the formals. The unmatched formal
arguments will be initialized to some garbage.
3) Any mismatch in data types may also result in some garbage values.
8
This is very similar to the function header line except the terminating semicolon.
for ex:-
int mul(int m, int n);
Equally acceptable forms of declaration of mul function are.
int mul(int,int);
mul(int a, int b);
mul(int,int);
When a function does not take any parameters and does not return any value, its
prototype is written as:
void display(void);
A prototype declaration may be placed in two places in a program.
1. Above all the functions (including main)
2. inside a function definition.
When we place the declaration above all the functions, the prototype is referred to as
global prototype. Such declarations are available for all the functions in the program
When we place it in a function definition, the prototype is called the local prototype.
Such declarations are primarily used by the functions containing them.
The place of declaration of a function defines a region in a program in which the
function may be used by other functions. This region is known as the scope of the function.
9
{
printf(“y”);
}
void main()
{
void a(),b(),c(),d();
y();
a();
b();
c();
d();
}
void a()
{
printf(“A”);
y();
}
void b()
{
printf(“B”);
a();
}
void c()
{
10
a();
b();
printf(“C”);
}
void d()
{
printff(“D”);
c();
b();
a();
int swap(int,int);
void main()
{
int x,y;
printf(“Enter values of x&y”);
scanf(“%d%d”,&x,&y);
}
int swap(int a,int b)
{
int k;
k=a;
a=b;
b=k;
printf(“In swap(): x=%d y=%d”, a,b);
return 0;
}
Out put:
Enter values of x&y:5 4
In main() before swap() calling: x=5 y=4
In swap(): x=4 y=5
In main() after swap() called: x=5 y=4
2. call by reference: In this type instead of passing values , addresses are passed function
operates on addresses rather than values. Here the formal arguments are pointers to the actual
arguments. In this type formal arguments point to the actual argument. Hence changes made
in the arguments are permanent.
#include<stdio.h>
int swap(int*,int*);
void main()
{
int x,y;
printf(“\n Enter values of x&y”);
scanf(“%d%d”,&x,&y);
printf(“In main() before swap() calling: x=%d y=%d”,x,y);
swap(&x,&y);
*a=*b;
*b=*k;
printf(“\n In swap() x=%d y=%d”,*a,*b);
}
Output:-
Enter values of x&y:5 4
---------- control }
}
#include<stdio.h>
void add();
void main()
{
add();
}
void add()
{
int a,b;
scanf(“%d%d”,&a,&b);
printf(“%d”,a+b);
}
The main function has no control over the way the functions receive input data .we
could make the calling function to read data from terminal and pass it on the called function.
The nature of data communication between the calling function and the called
function with arguments but no return value.
main()
{
---------- value of argument func(a)
---------- {
func(a); -----------
14
---------- -----------
---------- no return values }
}
main()
---------
---------
---------
-----
}
#include<stdio.h>
void main()
{
int a,b;
void add(int,int);
printf(“enter a,b”);
scanf(“%d%d”,&a,&b);
add(a,b);
}
void add(int x,int y)
{
int z;
z=x+y;
printf(“%d”,z);
}
15
The nature of data communication between the calling function and the called
function with arguments and also return value.
main()
{
#include<stdio.h>
void main()
{
int a,b,c;
int add(int,int);
printf(“enter a,b);
scanf(%d%d”,&a,&b);
c=add(a,b);
printf(“%d”,c);
}
int add(int x, int y)
{
int z;
z=x+y;
return(z);
}
int c;
int add();
c=add();
printf(“%d”,c);
}
int add()
{
int x,y,z;
scanf(“%d%d”,&x,&y);
z=x+y;
return(z);
}
Recursion:
The function called by itself is called recursive function and this process is often
referred to as recursion.
Important Condition:
1. Each time a procedure calls itself, it must be nearer to a solution.
2. There must be a decision criterion for stopping the computation.
#include<stdio.h>
int fib(int n)
{
if(n<=1)
return n;
return fib(n-1)+fib(n-2);
}
void main()
{
int n;
printf(“enter n value”);
scanf(“%d”,&n);
printf(“\n%d th term of fibanocci series is %d”,n,fib(n));
}
#include<stdio.h>
int factorial(int);
void main()
{
17
int no,temp;
printf("Enter the no \n");
scanf("%d",&no);
temp=factorial(no);
else
return (x*factorial(x-1));
}
Header Files:
In C, a number of Pre-defined functions are available to perform various tasks. To use
these functions, we have to include the corresponding header file in which the function is
available.
When any of the functions getchar(), gets(), puts(), putchar(), getchar(), printf(),
scanf() is used the header file stdio.h has to be included.
1. Pow():
Syntax: pow(x,n);
Eg: pow(5,3)=53=125
2. sqrt():
Syntax: sqrt(n);
Eg: sqrt(81)=9
3. log():
Syntax: log(n);
Eg: log(8);
4. log 10():
The function returns logarithm value of the given number to the base 10.
Eg: log 10=1
5. exp():
Syntax: exp(x);
Ex: exp(3);
e3;
6. ceil():
The function returns the next higher integer value of the number.
Syntax: ceil(n);
Eg: ceil(17.7)=18;
ceil(16.1)=17;
7. floor():
This function returns the integer value less than or equal to the given number.
Syntax: floor(n);
Eg: floor(17.7)=17
floor(16.1)=16
cos, acos, cosh, sin, asin, sinh, tanh
1) abs():
Syntax: abs(integer value);
Eg: abs(-17)=17
2) fabs():
The function returns absolute(modulus) of a given floating point.
Syntax: fabs(float value);
Eg: fabs(-17.6)=17.6
3) atoi():
The function converts the given string to an integer value.
Syntax: atoi(string);
Eg: atoi(“123”)=123
19
4).atof():
This function converts the given string into floating point value.
Syntax: atof(string);
Eg: atof(“123.56”)=123.560000
i. isalpha(): This function checks whether the given character is an alphabet or not. If it is an
alphabet, it returns a non-zero otherwise zero.
islower(‘b’) ->true(non-zero)
islower(‘A’) ->false(zero)
iii. isupper():
isupper(‘B’) ->true(non-zero)
isupper(‘q’) ->false(zero)
iv. toupper():
toupper(‘b’)=B ->true(non-zero)
toupper(‘q’)=Q ->false(zero)
v. toascii():
toascii(‘a’)=97
toascii(‘B’)=66
V string.h:
ARRAYS
Introduction:-
#include<stdio.h>
void main()
{
int a=2;
a=4;
printf(“%d”,a);
}
Output:- 4
a=2 is assigned before assigning 4 to it. When we assign 4 to ‘a’ then the value stored
in ‘a’ is replaced with the new value. Hence, ordinary variables can capable of storing one
value at a time. This fact is same for all data types. But in application the variables must be
assigned to more than one value. This can be possible with the help of “Arrays”.
Definition:-
Array is a collection of similar data types in which each element is unique one and
located in separate memory locations.
Declaration of an Array:-
Syntax:-
<datatype><arrayname>[size];
1. The data type specifies the type of elements that will be contained in the array such as
int, float & char.
2. Array name specifies all elements of an the array share the same name and they are
distinguished from one another with the help of an element number (or) index
number.
3. Size indicates the maximum number of elements that can be stored inside the array.
Initializing Array:-
Syntax:-
Here 5 elements are stored in an array ‘a’. The array elements are stored sequentially in
separate locations.
Array in ‘c’ language indexing starting at ‘0’.Reading of array elements begins from ‘0’.
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=8
1. If the number of values in the list is less than the number of elements, then only that
remaining elements will be set to zero automatically.
2. The size may be omitted. In such cases the compiler allocates enough space for all
initialized elements.
4. If the number of values in the list is greater than the number of elements, then produce
an error.
Ex:- int num[3]={10,20,30,40};
NOTE:-Compile time initialization may be partial i.e.., the number of initializers may
be less than the declared size. In such cases, the remaining elements are initialized to
zero, if array type is numeric & NULL if the type is char.
Drawback:-
There is no short cut method for initializing a large number of array elements.
Characteristics of An Array:-
1. The declaration int a[5] is nothing but creation of 5 variables of integer types in
the memory. Instead of declaring five variables for five values, the programmer
can define in an array.
2. All the elements in the array share the same name and they are distinguished
from one other with the help of element number.
3. The element number in an array plays major role for calling each element.
4. Any particular element of an array can be modified separately without
distributing other elements
int a[5]={1,2,3,4,8};
5. Any element of an array a[] can be assigned or equated to another ordinary
variable or array variable of its type.
Types of Array:-
We can represent not only simple lists of values but also tables of data in two, three or
more dimensions. To discuss how to use it to create and apply the following types of an
array.
A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a One-dimensional array.
To calculate the average of n values of x. The subscripted variable xi refers to the ith
element of x.
x[1],x[2],x[3],……,x[n]
int number[5];
number[0]
number[1]
number[2]
number[3]
number[4]
Let us give the values to the array elements to the array elements can be assigned as follows
number[0]=35;
number[1]=40;
number[2]=20;
number[3]=57;
number[4]=19;
number[0] 35
number[1] 40
24
number[2] 20
number[3] 57
number[4] 19
Memory Map With One-Dimensional Array:-
35 40 20 57 19
Syntax:
3001+44*2
3001+88
3089
#include<stdio.h>
void main
printf(“enter size:”);
25
scanf(“%d”, &n) ;
scanf(“%d”, &a[i]);
sum = sum+a[i];
Ex: Write a c program to find the duplicate numbers in a given list of numbers.
#include <stdio.h>
int main()
{
int n, a[n];
printf("Enter size of the array\n");
scanf("%d",&n);
printf("Enter elements of the array\n");
for(int i = 0;i <n;i++)
{
scanf("%d",&a[i]);
}
printf("Duplicate elements in the list are\n");
for(int i = 0;i <n;i++)
{
for(int j = i+1; j <n;j++)
{
if(a[i] == a[j])
{
printf("%d\n",a[i]);
}
}
}
}
Ex: Write a C Program to Increment every Element of the Array by one & Print
Incremented Array
#include <stdio.h>
void main()
{
26
int a[100],n,i;
printf("enter size");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
a[i]++;
for(i=0;i<n;i++)
printf("%d\t",a[i]);
2. Two-dimensional arrays:-
So far we have discussed the array variables that can store a list of values. There could be
situation where a table of values will have to be stored. Consider the following data table,
which shows the value of sales of 3 items by 4 sales girls
The table contains a total of 12 values, 3 in each line. This table as a matrix consisting of 4
rows and 3 columns.
<datatype><arrayname>[row-size][column-size];
Two-dimensional arrays are stored in memory, as shown in fig. As with the single
dimensional arrays, each dimension of the array is indexed from zero to its maximum size
minus one; the index selects the row and second index selects the column within that row.
Like the one-dimensional arrays, two dimensional arrays may be initialized by following
their declaration with a list of initial values enclosed in braces.
Initialize the elements of the first row to zero and second row to one.
{0, 0, 0},
{1, 1, 1}
};
When the array is completely initialized with all the values explicitly, we need not specify
the size of the first dimension.
{0, 0, 0},
{1, 1, 1}
};
If the values are missing in the initializer, they are automatically set to zero.
{1,1},
{2}
};
28
When all the elements are to be initialized to zero, the following short-cut method may be
used.
0 10 20 30
rows 1 40 50 60
2 70 80 90
0 1 2
columns
10 20 30
row0
40 50 60
row1
70 80 90
row2
Ex: There is an array a[3][4] and we have to find the address of a[2][2]
3001+(4*2+2)*2
3001+(10)*2
3022
#include <stdio.h>
void main()
{
int A[100][100], B[100][100], C[100][100], r, c, i, j;
printf ("Enter number of rows& columns\n ");
scanf("%d%d", &r, &c);
printf("\nEnter elements of A matrix:\n");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d",&A[i][j]);
}
}
printf("Enter elements of B matrix:\n");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d", &B[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
printf("\nSum of two matrixes is: \n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf ("%d\t ", C[i][j]);
}
printf (“\n”);
}
}
#include <stdio.h>
void main()
{
int A[10][10], B[10][10], C[10][10];
int m, n, p, q, i, j, k;
printf("Enter the number of rows and columns of A matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
{
printf("Matrices with entered orders can't be multiplied with each other.\n");
}
else
{
printf("Enter the elements of A matrix\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &A[i][j]);
}
}
printf("\n");
}
}
3. Multi-Dimensional arrays:-
Syntax:-
<datatype><array-name >[s1][s2][s3][s4]…….[sn];
Survey is a 3-D array declared to contain 180 integer type elements. Similarly table is
a 4-D array containing 300 elements of floating- point type .
MEMORY MAP:-
a[0][0][0]=1
a[0][0][1]=2
a[0][0][2]=3
a[0][1][0]=4
a[0][1][1]=5
a[0][1][2]=6
a[0][2][0]=7
a[0][2][1]=8
a[0][2][2]=9
a[1][0][0]=10
a[1][0][1]=11
a[1][0][2]=12
32
a[1][1][0]=13
a[1][1][1]=14
a[1][1][2]=15
a[1][2][0]=16
a[1][2][1]=17
a[1][2][2]=18