You are on page 1of 25

Functions in C:

 When we need to solve a large problem, we will divide that large problem into small sub
problems and solved individually to make the program easier.
 In C this is concept is implemented using functions.
 A function is a self contained block of statements that is used to carry out a particular task in a
program.
 Functions are used to divide a large program into smaller entities known as sub programs.
 Functions makes the program easy to understand and easy to implement.
 Functions increase the readability and execution speed of the program.
 Function supports reusability of the existing code.
 Every C program must have atleast one function i.e. main() and can have other functions.
In C there are 2 types of functions.
1. Predefined/Library functions: The functions that are already defined in C in header files.
2. User-defined functions: The functions that are defined and used by the programmer himself as per
his requirement are called user-defined functions.
Working with functions:
Working with functions includes 3 steps.
1. Function Declaration (Function Prototype)
2. Function Call
3. Function Definition
Function Declaration: The function declaration tells the interface of the function to the compiler such as
data type of the return value, name of the function, number and type of parameters it receive. The
function declaration is also called as function prototype. The function declaration is a declaration
statement. It can be before main function or inside main function at the beginning point or inside any
other function.
Syntax: returnType functionName( parametersList );
 returnType specifies the data type of the value that is sent as return value from the function.
 functionName is a name that is used to identify the function uniquely.
 parameterList contains number and type of values that are received by the functions as input.
Each parameter will have 2 parts, data type of the parameter and parameter name.
 Ex: int sum(int x,int y); Here int --> returnType, sum---> function Name, int x,int y -->
Parameters
 Each parameter must be specified individually and separately i.e. int sum(int x,int y);.
 Common declaration like int sum(int x,y) is illegal.
 In parametersList the parameter name if optional that means you can specify as int sum(int , int
);
Function Call: The function call invokes the definition of the function. It tells the compiler when to
execute the function definition. When a function is called, the execution control jumps to the function
definition where the function statements get executed and returns to the same functions call once the
execution completes. While calling a function we must pass all the necessary values through
parameters. .
Syntax - variable = functionName(parameters);
Ex: int s = sum(10,20); or int s = sum(a,b); Here 10 and 20, a and b are parameters.
Function Definition: The function definition contains a set of statements that are used to implement that
particular function's task. The function definition is also known as body of the function.

BHASKAR @ SRI SAI DEGREE COLLEGE


Syntax: returnType functionName(parametersList)
{
Statement-1;
------------------------ --- Function body
---------------------------
}
Example: int sum(int x,int y)
{
int z;
z = x + y;
return(z);
}

 Function definition's header is similar to function declaration and includes { } to define the
statements.
 In function definition the parameter names are must and they acts like dummy variables.
 The parameter names in function declaration and function definition need not to be same.
 Usually a function definition terminates with the "return" statement.
Advantages of functions:
 Using funcions we can implement modular programming.
 Functions makes the program more readable and understandable.
 Using functions the program implementation becomes easy.
 Once a function is created it can be used many times (code re-usability).
 Using functions larger program can be divided into smaller modules.
#include <stdio.h>
#include<conio.h>
int sum(int,int) ; // function declaration
void main()
{
int num1, num2, result ;
clrscr() ; Actual Arguments
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = sum(num1, num2) ; // function call Calling function
printf("SUM = %d", result);
getch() ; Forma Arguments
}
int sum(int a, int b) // function definition
{
int c; Called function
c = a + b;
return(c);
}
 In the above example program, the function declaration statement "int sum(int,int)" tells the
compiler that there is a function with name sum which takes two integer values as parameters
and returns an integer value.
 The function call statement takes the execution control to the sum() definition along with values
of num1 and num2.

BHASKAR @ SRI SAI DEGREE COLLEGE


 Then function definition executes the code written inside it and comes back to the function
call along with return value.
 In the concept of functions, the function call is known as "Calling Function" and the function
definition is known as "Called Function".
 The values transferred from calling function to called function are called as Parameters and the
value transferred from called function to calling function is called Return value.
Based on parameters and return value, functions are of 4 types.
 Function without Parameters and without Return value
 Function with Parameters and without Return value
 Function without Parameters and with Return value
 Function with Parameters and with Return value
Function without Parameters and without Return value
These functions do not have any parameters and return value. In this functions there is no data transfer
between calling function and called function. Simply the execution control jumps from calling function to
called function and execute called function, and finally come back to the calling function.
#include <stdio.h>
#include<conio.h>
void main()
{
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
Function with Parameters and without Return value
These functions can pass parameters but should not return any value. In this type of functions there is
data transfer from calling function to called function (parameters) but there is no data transfer from
called function to calling function (return value).
#include <stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

addition(num1, num2) ; // function call

getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}

BHASKAR @ SRI SAI DEGREE COLLEGE


Function without Parameters and with Return value
These functions should not have any parameters but have a return value. In this type of functions there
is no data transfer from calling function to called function (parameters) but there is data transfer from
called function to calling function (return value).
#include <stdio.h>
#include<conio.h>
void main()
{
int result ;
int addition() ; // function declaration
clrscr() ;

result = addition() ; // function call


printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
Function with Parameters and with Return value
These functions will have some parameters and a returns value also. In this type of functions there is
data transfer from calling function to called function (parameters) and also from called function to
calling function (return value).
#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

result = addition(num1, num2) ; // function call


printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
According to calling of a function, functions are of 2 types.
1. Call by Value 2. Call by reference
Call by Value
Calling a function by passing values as parameters is called as call by value mechanism. In call by
value mechanism the actual arguments / parameters of calling function will copied into formal
arguments / parameters of called function and these formal parameters are used in called
function. The changes made on the formal parameters do not affect the values of actual parameters.
That means, after the execution control comes back to the calling function, the actual parameter values
remains same.
#include <stdio.h>
#include <conio.h>
int factorial(int n);
void main()
{

BHASKAR @ SRI SAI DEGREE COLLEGE


int num, fact;
Output:
clrscr();
Enter a Number: 5
printf("Enter a Number ");
Factorial of 5 = 120
scanf("%d",&num);
Here num is called a actual parameter and n
fact = factorial(num);
printf("Factorial of %d = %d:,num,fact); is called as formal parameter.
getch(); The value of num is copied into n and
} working performed on n.
int factorial(int n) The change made in "n" will not effect the
{ actual parameter "num"
int f = 1; The value of "n" changed to 0 but the value
while( n != 0 ) of "num" is remained as same 5.
{
f = f * n;
n--;
}
return(f);
}
Call by Reference
Calling a function by passing references (memory location addresses) is called as Call by reference
mechanism. In Call by Reference method, the formal arguments of called function will become
references to the actual parameters of calling function. That means in call by reference parameter
passing method, the address of the actual parameters is passed to the called function and is received
by the formal parameters (pointers). Whenever we use these formal parameters in called function,
they directly access the memory locations of actual parameters. So the changes made on the formal
parameters effects the values of actual parameters directly.
#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;


swap(&num1, &num2) ; // calling function

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
void swap(int *m, int *n) // called function
{
int temp ;
temp = *m ;
*m = *n ;
*n = temp ;
}
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
In the above example program, the addresses of variables num1 and num2 are copied to pointer
variables m and n. The changes made on the pointer variables m and n in called function effects the
values of actual parameters num1 and num2 in calling function.

BHASKAR @ SRI SAI DEGREE COLLEGE


Recursive Function / Function Recursion
In C, function calling can be made from main() function, other functions or from same function itself. A
function which calls itself is called as recursive functions. When a function is called by itself, the first call
remains under execution till the last call gets invoked. Every time when a function call is invoked, the
function returns the execution control to the previous function call.
The recursive functions should be used very carefully because; when a function called by itself it enters
into infinite loop and when a function enters into the infinite loop, the function execution never gets
completed.
#include <stdio.h>
#include<conio.h>
int factorial( int ) ;
void main( )
{
int fact, num ;
printf(“Enter any positive integer: ”);
scanf(“%d”, &num) ;
fact = factorial( num ) ;
printf(“Factorial of %d is %d”, num, fact) ;
}
int factorial( int n )
{
int temp ;
if( n == o)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}
Output:
Enter any positive integer: 3
Factorial of 3 is 6
Types of recursion
 Direct Recursion
 Indirect Recursion
Direct Recursion
A function is said to be direct recursive if it calls itself directly.
Example: C Program Function to show direct recursion
int fibo (int n)
{
if (n==1 || n==2)
return 1;
else
return (fibo(n-1)+fibo(n-2));
}
In this program, fibo() is a direct recursive function. This is because, inside fibo() function, there is a
statement which calls fibo() function again directly.
Indirect Recursion
A function is said to be indirect recursive if it calls another function and this new function calls the
first calling function again.
Example : C Program Function to show indirect recursion
int func1(int n)
{
if (n<=1)
return 1;
else
return func2(n);
}

BHASKAR @ SRI SAI DEGREE COLLEGE


int func2(int n)
{
return func1(n);
}
Disadvantages of Recursion
 Recursive programs are generally slower than non recursive programs because it needs to make
a function call so the program must save all its current state and retrieve them again later. This
consumes more time making recursive programs slower.
 Recursive programs require more memory to hold intermediate states in a stack. Non recursive
programs don't have any intermediate states, hence they don't require any extra memory.
Difference between Recursion and Iteration
Recursion and iteration both repeatedly executes the set of instructions. Recursion is when a statement
in a function calls itself repeatedly. The iteration is when a loop repeatedly executes till the controlling
condition becomes false. The primary difference between recursion and iteration is that is
a recursion is a process, always applied to a function. The iteration is applied to the set of instructions
which we want to get repeatedly executed.
Towers of Hanoi
#include <stdio.h>
// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}

int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}
Scope of variables:
Scope of a variable is the portion of the program where a defined variable can be accessed.
The variable scope defines the visibility of variable in the program. Scope of a variable depends on
the position of variable declaration.
 Global Declaration (Before the function definition)
 Local Declaration (Inside the function or block)
Global Declaration (Global Variables)
Declaring a variable before the function definition (outside the function definition) is called global
declaration. The variable declared using global declaration is called global variable. The global
variable can be accessed by all the functions that are defined in the program.
#include <stdio.h>
#include<conio.h>
int num1, num2 ;
void main(){
void addition() ;
void subtraction() ;
void multiplication() ;
clrscr() ;

BHASKAR @ SRI SAI DEGREE COLLEGE


num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
subtraction() ;
multiplication() ;
getch() ;
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ;
printf("\nsubtraction = %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}

Output:
num1 = 10, num2 = 20
addition = 30
subtraction = -10
multiplication = 200
In the above example program, the variables num1 and num2 are declared as global variables. They
are declared before the main() function. So, they can be accessed by function main() and other
functions that are defined after main(). In the above example, the functions main(), addition(),
subtraction() and multiplication() can access the variables num1 and num2.
Local Declaration (Local Variables)
Declaring a variable inside the function or block is called local declaration. The variable declared
using local declaration is called local variable. The local variable can be accessed only by the function
or block in which it is declared. That means the local variable can be accessed only inside the function.
#include <stdio.h>
#include<conio.h>
void main(){
void addition() ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
getch() ;
}
void addition()
{
int sumResult ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
Output:

BHASKAR @ SRI SAI DEGREE COLLEGE


ERROR
The above example program shows an error because, the variables num1 and num2 are declared
inside the function main(). So, they can be used only inside main() function and not in addition() function.
Storage Classes:
Every variable in C programming has two properties: type and storage class. Type refers to the data
type of a variable. And, storage class determines the scope and lifetime of a variable.
There are 4 types of storage class:
 automatic
 external
 static
 register
auto storage class:
The variables that are declared with the keyword "auto" are automatic variables. Their life time and
scope is within the function in which they are declared. They are created every time a function is called
and destroy when function is exited. All local variables are automatic variables.
int main() {
int n; // n is a local variable to main() function
... .. ...
}

void func() {
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when main() exits.
extern storage class:
The variables that are declared with "extern" are external variables. Their life time and scope is entire
program. They are created when the program execution begin and remains until the program
termination. all the global variables are extern variables.
#include <stdio.h>
void display();
extern int n = 5; // global variable
int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}
void display()
{
++n; // variable n is not declared in the display() function
printf("n = %d", n);
}
Output
n=7
Register Variable
The register keyword is used to declare register variables. The memory for the register variables are
allocated in register memory location instead of RAM. Register variables were supposed to be faster
than local variables. Using of register variables will make program faster.

BHASKAR @ SRI SAI DEGREE COLLEGE


Static Variable
A static variable is declared by using keyword static. The static variables scope is within the function in
which it is declared but its life time is entire program. Unlike auto (local) variables they are not
destroyed when a function exited, they remains until the program is terminated.
static int i;
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf("%d ",c);
c += 5;
}
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It's because c is a static variable.
So, 5 is displayed on the screen.
Suppression Character in Scanf()
If we want to skip any input field then we specify * between the % sign and the conversion
specification. The input field is read but its value is not assigned to any address. This character
* is called the suppression character. For example-
scanf("%d %*d %d",&a, &b, &c);
Input
a=25 , b=30 ,c=35
Here 25 is stored in a, 30 skipped and 35 is stored in the b, since no data is available for c so
it has garbage value.
scanf("%d %*c %d %*c %d",&d, &m, &y);
Input :
3/1/2003
Here 3 will be stored in d, then / will be skipped , 11 will be stored in m, again / will be
skipped and finally 2003 will be stored in y.
Sparse Matrix:
In computer programming, a matrix can be defined with a 2-dimensional array. Any array with
'm' columns and 'n' rows represents a m X n matrix. There may be a situation in which a matrix
contains more number of ZERO values than NON-ZERO values. Such matrix is known as sparse
matrix.
Sparse matrix is a matrix which contains very few non-zero elements.

BHASKAR @ SRI SAI DEGREE COLLEGE


#include <stdio.h>
void main ()
{
static int array[10][10];
int i, j, m, n;
int counter = 0;
printf("Enter the order of the matix \n");
scanf("%d %d", &m, &n);
printf("Enter the co-efficients of the matix \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
if (array[i][j] == 0)
{
++counter;
}
}
}
if (counter > ((m * n) / 2))
{
printf("The given matrix is sparse matrix \n");
}
else
printf("The given matrix is not a sparse matrix \n");
printf("There are %d number of zeros", counter);
}
Generic Pointers
We know that pointers are strictly typed. i.e we cannot assign an integer memory address to
float *.
1. int x = 5;
2. float* fp = &x; // ERROR
3. int *ip = &x; // OK

BHASKAR @ SRI SAI DEGREE COLLEGE


a pointer type that can hold the address of any data type. When a variable is declared as
being a pointer to type void it is known as a generic pointer.
1. int x = 5;
2. float y = 3.5;
3. void* vp; // GENERIC POINTER
4.
5. vp = &x; // OK
6. vp = &y; // OK
Error Handling During I/O Operations
While writing programs which involve accessing files, certain errors might occur while
performing I/O operations on a file. Some of the error situations include the following:
1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, when the file is being use by another
application.
5. Opening a file with invalid name.
6. Attempting to write to write-protected file.
If such errors are unchecked, it may lead to abnormal termination of the program or may lead
to incorrect output. C library provides two functions namely feof and ferror for handling the
above mentioned situations.
The feof() function is used to test for the end-of-file condition. It takes a file-pointer as a
parameter and returns a non-zero integer value if all of the data from the specified file has
been read, and returns zero otherwise. The syntax is as shown below:
Syntax: int feof(file-pointer)
The ferror() function reports the status of the file. It takes a file-pointer as its argument and
returns a non-zero integer if an error has been detected up to that point, or
returns zero otherwise. The syntax is as shown below:
Syntax: int ferror(file-pointer)
Whenever a file is opened using fopen() function, a file pointer is returned. If the file cannot be
opened for some reason, the function returns a NULL pointer. This can be used to test whether
the file has been opened successfully or not. It can be used as shown below:
if(fp == NULL)
printf(“File cannot be opened!”);

BHASKAR @ SRI SAI DEGREE COLLEGE


Random Access to Files
All the functions that we have seen so far are useful for reading and writing data sequentially
to and from a file. Sometimes the user might want to access data at random locations from a
file. For this purpose, C library provides functions namely: ftell, fseek and rewind.
The ftell() function lets the user to know the current location of the file pointer. It takes a file-
pointer as a parameter and returns a long integer that corresponds to the current position of
the pointer. Syntax is a shown below:
1 long ftell(file-pointer)
The rewind() function lets the user to move the file pointer again to the beginning of the file.
This function accepts a file-pointer as a parameter and resets the position to the start of the
file. This helps us in reading a file more than once, without having to close and reopen the file.
Syntax is as follows:
1 rewind(file-pointer)
The fseek() function is used to move the pointer to any position within the file. This function takes
three parameters: file-pointer, offset and position. When the operation is
successful, fseek() returns a non-zero value. If we attempt to move the file pointer beyond the
file boundaries, an error occurs and fseek returns a -1. Syntax is as follows:
1 fseek(file-pointer, offset, position)
The offset is a number of the type long, and position is an integer number. The offset represents
the number of positions to be moved from the location specified by position. The position can
take one of the following values:

A positive value for the offset specifies that the pointer moves forward and a negative value
for the offset specify that the pointer moves backward from the current position. Following are
some of the example usages of the fseekfunction:

How to rename a file in c programming


The rename() function is not only appropriately named but it’s also pretty simple to figure out:

BHASKAR @ SRI SAI DEGREE COLLEGE


x = rename(oldname,newname);
oldname is the name of a file already present; newname is the file’s new name. Both values can
be immediate or variables. The return value is 0 upon success; -1 otherwise.
How to delete a file in c programming
Programs delete files all the time, although the files are mostly temporary anyway. If your
code creates temporary files, remember to remove them before the program quits. The way to
do that is via the unlink() function. The return value is 0 upon success; -1 otherwise.

Command Line Arguments


The values or arguments that are passed from the command prompt while running a C Program
are called command line arguments. These parameters are the additional information like
filename or other kind of input to the program. By passing command line arguments there is no
need for the user to provide the input while executing the program.
These command line arguments can be processed by using the arguments available in
the main function. The main allows two parameters namely: argcand argv.
The argc represents the argument counter which contains the number of arguments passed in the
command line.
The argv is a character pointer array which points to the arguments passed in the command
line.
To know the number of command line arguments, we can use the argc parameter of
the main function and to access the individual arguments, we can use the argv array. The first
element in the argv array is always the program name. So the first argument can be accessed
by using argv[1] and so on. The main function will be as shown below:
main(int argc, char *argv[ ])
{
-----
-----
}

BHASKAR @ SRI SAI DEGREE COLLEGE


Break and Continue Statements in C:
Break statement (break)
 Sometimes it becomes necessary to come out of the loop even before loop condition
becomes false then break statement is used.
 Break statement is used inside loop and switch statements.
 It cause immediate exit from that loop in which it appears and it is generally written with
condition.
 It is written with the keyword as break.
 When break statement is encountered loop is terminated and control is transferred to the
statement, immediately after loop
 When break is encountered inside any loop, control automatically passes to the first
statement after the loop.
 This break statement is usually associated with if statement.
Example:
void main()
{
int n;
for(n=0;n<=9; n++)
{
if(n==4)
break;
printf(“%d”, n);
}
}
Printf(“out of loop”);
}
Output:
0123
out of loop
Continue statement (continue)
 Continue statement is used for continuing next iteration of loop after skipping some
statement of loop.
 When it encountered control automatically passes through the beginning of the loop.
 It is usually associated with the if statement.
 It is useful when we want to continue the program without executing any part of the
program.
 The difference between break and continue is, when the break encountered loop is
terminated and it transfer to the next statement and when continue is encounter control
come back to the beginning position.
 In while and do while loop after continue statement control transfer to the test condition
and then loop continue where as in, for loop after continue control transferred to the
updating expression and condition is tested.

BHASKAR @ SRI SAI DEGREE COLLEGE


Example:
void main()
{
int n;
for(n=1;n<=9; n++)
{
if(n==4)
continue;
printf(“%d”, n);
}
}
Printf(“out of loop”);
}
Output:
12 3 5 6 7 8 9
Out of loop
Function Pointer: We know that a pointer means pointer variable which can store the address of a
variable or memory location. In C we can declare a pointer which can store the address of a function.
The pointer that can store the address of a function is called as Function Pointer.
Declaring a function pointer:
To declare a pointer we must specify the return_type of function and Parameter list along with * and
pointer name.
Syntax: returnType (*pointer_name(paramtersList);
Ex: We have a function int sum(int a,int b); then the function should be declared as
int (*fp)(int , int );
 Here the int is return type
 for specifying the pointer, fp is the pointer name
 (int , int ) is the parameterList
Assigning function to a pointer:
After declaring a function pointer we must assign the address of the function into the function pointer. It
is as like assigning address of a variable into pointer.
Syntax: function_pointer = &fun_name;
Ex: fp = &sum; Here fp is fucntion pointer and sum is the function name and & is address of operator
We can combine the above 2 steps as following
returnType (*pointer_name)(ParametersList) = &function_name;
int (*fp) = &sum;
While assigning function to a pointer the & is optional. Because the function itself refers an address.
Hence you can also use like fp = sum; where fp is function pointer and sum is the function name.
Calling a function using function pointer:
We can call the function through function pointer as like calling a function i.e. by passing the
parameters using function pointer.
Syntax: function_pointer(parameters);
Ex: int s = fp(10, 20);
Array of function pointer:
An array of function pointers can be created for the functions of same return type and taking same
type and same number of parameters. For example, if we have four function definitions for
performing basic arithmetic operations (addition, subtraction, multiplication, and division) on two
integer values, all these functions will take two integer arguments and will return an integer as a result.

BHASKAR @ SRI SAI DEGREE COLLEGE


For such similar~return~type~and~argument operations you can create an array of function pointers
and select a proper function by its index rather than its name. The following example demonstrates it.

#include <stdio.h>
int getSum(int, int);
int getDifference(int, int);
int getProduct(int, int);
int getDivision(int, int);
int main()
{
int (*arrayFp[4])(int, int);
arrayFp[4] = {getSum, getDifference, getProduct, getDivision};
int a = 50, b = 20;
printf("Sum of %d and %d : %d\n", a, b, arrayFp[0](a, b));
printf("Difference of %d and %d : %d\n", a, b, arrayFp[1](a, b));
printf("Product of %d and %d : %d\n", a, b, arrayFp[2](a, b));
printf("Division of %d and %d : %d\n", a, b, arrayFp[3](a, b));
}
int getSum(int x, int y)
{
return x + y;
}
int getDifference(int x, int y)
{
return x - y;
}
int getProduct(int x, int y)
{
return x * y;
}
int getDivision(int x, int y)
{
return x / y;
}

Calculating the size of an array:


We can find the size of an array or elements declared in an array by using size of operator.
size = sizeof(array_name) / sizeof(array_data_type);
Ex: If we declare an array as int num[5];
size = sizeof(num) / sizeof(int);
Here array occupies 10 bytes of memory and size of int is 2 hence 10 / 2 = 5 is the size.
Passing array as an argument
If we want to pass a single-dimension array as an argument in a function, we would have to declare a
formal parameter in one of following three ways and all three declaration methods produce similar
results
Way-1
Formal parameters as a pointer −
void myFunction(int *param) {
.
.

BHASKAR @ SRI SAI DEGREE COLLEGE


.
}
Ex:
void getSum(int *p, int size)
{
int i,s = 0;
for( i = 0; i < size; i++)
s = s + *(p+i);
return(s);
}
Way-2
Formal parameters as a sized array −
void myFunction(int param[10]) {
.
.
.
}
void getSum(int a[10], int size)
{
int i,s = 0;
for( i = 0; i < size; i++)
s = s + a[i];
return(s);
}
Way-3
Formal parameters as an unsized array −
void myFunction(int param[]) {
.
.
.
}
void getSum(int a[], int size)
{
int i,s = 0;
for( i = 0; i < size; i++)
s = s + a[i];
return(s);
}
Pointer to Pointer
In C pointer to pointer concept, a pointer refers to the address of another pointer.
In c language, a pointer can point to the address of another pointer which points to the address of a
value. Let's understand it by the diagram given below:

Syntax: int **p2;

BHASKAR @ SRI SAI DEGREE COLLEGE


C pointer to pointer example
Let's see an example where one pointer points to the address of another pointer.

Pointer Arithmetic in C
In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable.
 Increment
 Decrement
 Addition
 Subtraction
 Comparison
Incrementing Pointer in C
Increment operation depends on the data type of the pointer variable. The formula of incrementing
pointer is
new_address= current_address + i * size_of(data type)
 For 32 bit int variable, it will increment to 2 byte.
 For 64 bit int variable, it will increment to 4 byte.
Decrementing Pointer in C
We can decrement a pointer variable. The formula of decrementing pointer is given below:
new_address= current_address - i * size_of(data type)
 For 32 bit int variable, it will decrement to 2 byte.
 For 64 bit int variable, it will decrement to 4 byte.
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
new_address= current_address + (number * size_of(data type))
 For 32 bit int variable, it will add 2 * number.
 For 64 bit int variable, it will add 4 * number.
C Pointer Subtraction
We can subtract a value from the pointer variable. The formula of subtracting value from pointer
variable is given below:
new_address= current_address - (number * size_of(data type))
 For 32 bit int variable, it will subtract 2 * number.
 For 64 bit int variable, it will subtract 4 * number.
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of <stdlib.h>
 malloc()
 free()
Before learning above functions, let's understand the difference between static memory allocation and
dynamic memory allocation.
Static memory allocation Dynamic memory allocation

BHASKAR @ SRI SAI DEGREE COLLEGE


Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while executing Memory can be increased while executing
program. program.
Used in array. Used in linked list.

malloc() allocates single block of requested memory.


free() frees the dynamically allocated memory.
malloc() function in C
The malloc() function allocates single block of requested memory.
It doesn't initialize memory at execution time, so it has garbage value initially.
It returns NULL if memory is not sufficient.
Syntax: ptr=(cast-type*)malloc(byte-size)
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Syntax: free(ptr);
Pointers And Arrays
In C there is a very close connection between pointers and arrays. In fact they are more or less one
and the same thing! When you declare an array as:
int a[10];
 In fact declaring a pointer a to the first element in the array. That is, a is exactly the same
as &a[0].
 The only difference between a and a pointer variable is that the array name is a constant
pointer - we cannot change the location it points at.
 When you write an expression such as a[i] this is converted into a pointer expression that gives
the value of the appropriate element.
 To be more precise, a[i]is exactly equivalent to *(a+i) i.e. the value pointed at by a + i . In the
same way *(a+ 1) is the same as a[1] and so on.
 Being able to add one to a pointer to get the next element of an array is a nice idea, but it
does raise the question of what it means to add 'one' to a pointer.
 For example, in most implementations an int takes two memory locations and a float takes four.
So if you declare an int array and add one to a pointer to it, then in fact the pointer will move
on by two memory locations.
 However, if you declare a float array and add one to a pointer to it then the pointer has to
move on by four memory locations. In other words, adding one to a pointer moves it on by an
amount of storage depending on the type it is a pointer to.
Structures in C:
A structure is a derived data type that is used to declare the variables of different data types in
sequence. It is used to bind the logically related data items of different types. Structures are used to
work with records.
Declaring a structure:
The structure declaration start with the keyword "struct" along with structureName or structureTag and
contains a set of variables which are called as structure members.
Syntax: struct structureName
{
data_type member1;
data_type memebr2;
data_type member3;
} [structureVariable1,structureVariable2,....]; The structure variable is optional.

BHASKAR @ SRI SAI DEGREE COLLEGE


Ex: struct Student
{
int rollNo;
char name[20];
float avg;
}; It will declare a structure with 3 members rollNo, name and avg;
A structure member can be a variable, an array, a pointer or any structure.
Structure Variable Creation:
The structure declaration only specify the members of the structure, no memory is allocated to the
structure members. The necessary memory for the member of a structure is allocated when we declare
a variable to that structure. The structure variable can be created while declaring the structure.
struct Student
{
int rollNo;
char name[20];
float avg;
}sVar; Here sVar is a structure variable that holds memory for rollNo, name and avg.
We can also declare a structure variable after declaring a structure.
Syntax: struct structureName strVar;
Ex: struct Student sVar;
Accessing the members of a structure:
To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we
wish to access.
Syntax: strVar.memebrName;
Ex: sVar.rollNo = 1001;
Array of structure:
C Structure is collection of different data types (variables) which are grouped together. Whereas,
array of structures is nothing but collection of structures. This is also called as structure array in C. Array
of structure is used to work with group of records.
Syntax: struct structureName strArray[Size];
Ex: struct Student sArr[5];
Now we will get 5 structure variables to Student structure, each one can store an individual student
records. They can be accessed as sArr[0], sArr[1], sArr[2],...
Passing a structure to function:
In C, structure can be passed to functions by two methods:
 Passing by value (passing actual value as argument)
 Passing by reference (passing address of an argument)
Passing structure by value
A structure variable can be passed to the function as an argument as a normal variable.
If structure is passed by value, changes made to the structure variable inside the function definition
does not reflect in the originally passed structure variable.
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void display(struct student stu);
int main()

BHASKAR @ SRI SAI DEGREE COLLEGE


{
struct student stud;
printf("Enter student's name: ");
scanf("%s", &stud.name);
printf("Enter roll number:");
scanf("%d", &stud.roll);
display(stud); // passing structure variable stud as argument
return 0;
}
void display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Passing structure by reference
The memory address of a structure variable is passed to function while passing it by reference.
If structure is passed by reference, changes made to the structure variable inside function definition
reflects in the originally passed structure variable.
#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);
add(dist1, dist2, &dist3);
printf("\nSum of distances = %d\'-%.1f\"", dist3.feet, dist3.inch);
return 0;
}
void add(struct distance d1,struct distance d2, struct distance *d3)
{
d3->feet = d1.feet + d2.feet;
d3->inch = d1.inch + d2.inch;
if (d3->inch >= 12) { /* if inch is greater or equal to 12, converting it to feet. */
d3->inch -= 12;
++d3->feet;
}
}

BHASKAR @ SRI SAI DEGREE COLLEGE


Pointer to structure
Structures can be created and accessed using pointers. A pointer variable of a structure can be
created as below:
struct name {
member1;
member2;
.
.
};

int main()
{
struct name *ptr;
}
Here, the pointer variable of type struct name is created.
Accessing structure's member through pointer
Structure pointer member can also be accessed using -> operator.
 (*personPtr).age is same as personPtr->age
 (*personPtr).weight is same as personPtr->weight
Self referential structure:
The structure that represents itself is called as a referential structure. It is done by creating a pointer to
the structure as a member in the same structure and assigning the address of structure variable to that
pointer.
Example:
struct Node
{
int data;
struct Node *link;
}*nOne;
link = &nOne;
Here the link is pointer of struct Node that represent the nOne which is the Node structure's variable.
Union:
 Union is also a derived data type that is used to declare variables of different types.
 But it occupies common memory for all members of the union.
 It occupies in which data type the largest memory is declared as the common memory
 It accepts any type of value into that memory.
 But when we enter a new value the previous value will be erased.
Enumeration (or enum) in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.
enum State {Working = 1, Failed = 0};
The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an example
of enum declaration.
// The name of enumeration is "flag" and the constant
// are the values of the flag. By default, the values
// of the constants are as follows:
// constant1 = 0, constant2 = 1, constant3 = 2 and
// so on.
enum flag{constant1, constant2, constant3, ....... };

BHASKAR @ SRI SAI DEGREE COLLEGE


Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is
// defined as the variable of type week.

enum week{Mon, Tue, Wed};


enum day;

// Or

enum week{Mon, Tue, Wed}day;

File Handling in C
A file is a collection of information stored on a particular area of the disk. Till now we only work with
internal memory i.e. RAM which can store data temporarily. If we want to store data in the computer
memory permanently, then we use the concept of Files.
File operations include the following:
 Creation of a new file / Opening an existing file
 Reading from file / Writing to a file
 Closing a file
Opening or creating file –
For opening a file, fopen function is used with the required access modes. Some of the commonly used
file access modes are:
 “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. If the file cannot be opened fopen( ) returns
NULL.
 “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open file.
 “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer that points to the last character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
 “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. Returns NULL, if unable to open the file.
 “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new
file is created. Returns NULL, if unable to open file.
“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns
NULL, if unable to open file.
FILE *fp;
So, the file can be opened as
fp = fopen(“fileName.txt”, “w”)
Reading from a file
The file read operations can be performed using functions fscanf() or fgets(). Both the functions
performed the same operations as that of printf() and gets but with an additional parameter, the file
pointer. So, it depends on you if you want to read the file line by line or character by character.
And the code snippet for reading a file is as:
FILE * fp;
fp = fopen(“fileName.txt”, “r”);
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
Writing a file

BHASKAR @ SRI SAI DEGREE COLLEGE


The file write operations can be performed by the functions fprintf() and fputs() with similarities to read
operations. The snippet for writing to a file is as :
FILE *fp ;
fp = fopen(“fileName.txt”, “w”);
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012);
Closing a file After every successful fie operations, you must always close a file. For closing a file, you
have to use fclose() function.
FILE *fp ;
fp= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fp)
fprintf() function
The fprintf()is used to write formatted data such as strings, integers, float etc., into a file.
Syntax: fprintf(file_pointer,"format_specifier",variable);
Ex: fprintf(fp,"%d\t%s]t%f\n",rollno,name,avg);
fscanf() : This function is used to read formatted data like string. integer, float etc., from a file.
Syntax: fscanf(file_pointer,"format_specifier",&variable);
Ex: fprintf(fp,"%d\t%s]t%f\n",&rollno,&name,&avg);

BHASKAR @ SRI SAI DEGREE COLLEGE

You might also like