0% found this document useful (0 votes)
37 views115 pages

C Programming Functions Explained

The document provides an overview of functions in C programming, including types of functions such as library and user-defined functions, their advantages, and how they work. It explains parameter passing techniques, recursion, storage classes, and structures, detailing their definitions, examples, and usage. Additionally, it covers unions and their characteristics, emphasizing the importance of modularity and code reusability in programming.

Uploaded by

boddu.kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views115 pages

C Programming Functions Explained

The document provides an overview of functions in C programming, including types of functions such as library and user-defined functions, their advantages, and how they work. It explains parameter passing techniques, recursion, storage classes, and structures, detailing their definitions, examples, and usage. Additionally, it covers unions and their characteristics, emphasizing the importance of modularity and code reusability in programming.

Uploaded by

boddu.kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

“Unit-3”

1
Functions
• A function is a block of code that performs a particular task.
• A function can be called multiple times to provide reusability and
modularity to the C program.
• Dividing a larger program into various subprograms are called as
functions or modules.
Types of Functions
There are two types of functions in C programming:
[Link] Functions: are the functions which are declared in the C
header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
[Link]-defined functions: are the functions which are created by the
C programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.

Functions

Built-in User-defined
Functions Functions
Functions
Advantages of user-defined function:
• A large program can be divided into smaller modules. Hence, a
large project can be divided among many programmers.
• It makes your code reusable. You just have to call the function by
its name to use it, wherever required.
• In case of large programs with thousands of code lines, debugging
and editing becomes easier if you use functions.
• It makes the program more readable and easy to understand.
How User Defined function works
3 Elements of User defined functions
SNo C Function Syntax
Element
1 Function declaration return_type function_name (argument
list);

2 Function call function_name (argument_list);

3 Function definition return_type function_name (argument


list)
{
function body;
}
Example of User defined functions
Categories of Functions
Function Parameter and Function Argument
A parameter is a variable that we use in a function definition.
An argument is the actual data that we pass to the function
parameter.

User defined function are categorized in four categories:

• Function with no argument and no return value


• Function with no argument but returns a value
• Function with argument but no return value
• Function with argument and returns a value
Function with no argument and no return
value
Function with no argument and no return
value
#include<stdio.h>
void add( ) ; // function declaration
void main( )
{
add( ) ; // function call
}
void add( ) // function definition
{
int a, b, sum ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &a, &b);
sum=a+b;
printf(“sum = %d", sum ) ;
}
Function with no argument but returns a value
Function with no argument but returns a value
#include<stdio.h>
int add( ) ; // function declaration
int main( )
{
int sum ;
sum = add() ; // function call
printf(“sum = %d", sum) ;
return 0;
}
int add( ) // function definition
{
int a, b,sum ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &a, &b);
sum=a+b;
return sum ;
}
Function with argument but no return value
Function with argument but no return value
#include<stdio.h>
void add(int a, int b) ; // function declaration
void main()
{
int a, b ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &a, &b);
add(a, b) ; // function call
}
void add(int a, int b) // function definition
{
int sum;
sum=a+b;
printf(“sum = %d", sum ) ;
}
Function with argument and returns a value
Function with argument and returns a value
#include<stdio.h>
int add(int a, int b) ; // function declaration
int main()
{
int a,b,sum ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &a, &b);
sum = add(a, b) ; // function call // calling function
printf("Sum = %d", sum) ;
return 0 ;
}
int add(int a, int b) // function definition // called function
{
int sum;
sum= a+b;
return sum;
Passing Parameters to Functions/Parameter
Passing
Techniques
There are two types of parameters and they are as follows...
Actual Parameters
Formal Parameters
The actual parameters are the parameters that are specified in calling
function.
The formal parameters are the parameters that are declared at called
function.
When a function gets executed, the copy of actual parameter values are
copied into formal parameters.

There are two methods to pass parameters from calling function to called
function and they are as follows...

[Link] by Value/ Pass by value


[Link] by Reference/ Pass by reference
Call by Value/Pass by value
• In call by value parameter passing method, the copy of actual
parameter values are copied to formal parameters and these formal
parameters are used in called function.
• The changes made on the formal parameters does not effect the
values of actual parameters.
• After the execution control comes back to the calling function, the
actual parameter values remains same.
Call by Value Example
#include<stdio.h>
void swap(int x, int y) ; // function declaration
void main()
{
int a, b ;
a = 10 , b = 20 ;
printf("\n Before swap: a = %d, b = %d\n", a, b) ;
swap(a,b) ; // calling function a,b : actual parameters
}
void swap(int x, int y) // called function x,y: formal parameters
{
int temp ;
temp = x ;
x=y;
y = temp ;
printf(“ After swap : x=%d, y=%d\n”,x,y);
Call by Reference/Pass by reference
• In Call by Reference parameter passing method, the memory
location address of the actual parameters is copied to formal
parameters.
• This address is used to access the memory locations of the actual
parameters in called function.
• 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.
Call by Reference Example
#include<stdio.h>
void swap(int *x, int *y) ; // function declaration
void main()
{
int a, b ;
a = 10 , b = 20 ;
swap(&a, &b) ; // calling function
printf(“swap a=%d\n b=%d\n”,a,b);
}
void swap(int *x, int *y) // called function
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
printf("\nAfter swap: x = %d, y= %d", x, y);
}
Passing Arrays to Functions
#include<stdio.h>
int findSum(int marks[]);
void main()
{
int sum;
int marks[] = {99, 90, 96, 93, 95};
sum = findSum(marks);
printf(“Sum of marks = %d", sum);
}
int findSum(int marks[])
{
int i,sum=0;
for (i = 0; i <= 4; i++) {
sum += marks[i];
}
return sum;
}
Standard Functions and Libraries
Header Example
Purpose
File Functions
stdio.h Standard I/O operations printf(), scanf()

conio.h Console I/O operations clrscr(), getch()

math.h Mathematical operations sqrt(), pow()

string.h String Handling Functions strlen(), strcpy()

stdlib.h General functions/td> calloc(), malloc()

time.h Operations on time and date time(), localtime()

Testing and mapping of character isalpha(), islower()


Recursion
A function that calls itself is known as a recursive function.
Recursion Example
#include<stdio.h>
int factorial( int n ) ;
int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("\nFactorial of %d is %d\n", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
return n * factorial( n-1 ) ; // recursive function call
Recursion Implementation
Advantages and Limitations of
Recursion
Advantages
• Reduce unnecessary calling of function.
• Through Recursion one can Solve problems in easy way while its
iterative solution is very big and complex.
Limitations
• Recursive solution is always logical and it is very difficult to
trace.(debug and understand).
• In recursive 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.
• Recursion takes a lot of stack space, usually not considerable when
the program is small and running on a PC.
Storage Classes
Storage classes in C are used to determine the lifetime, visibility,
memory location, and initial value of a variable. There are four
types of storage classes in C:
• Automatic
• External
• Static
• Register
Storage Classes
Storage Classes : auto
#include<stdio.h>
void main ( )
{
auto int a =100;
{
auto int a = 300;
{
auto int a = 500;
printf (“\n\n\t a=%d”,a);
}
printf (“\n\n\t a=%d”,a);
}
printf (“\n\n\t a=%d”, a);
}
O/p: a = 500 a = 300 a = 100
Storage Classes : extern
#include<stdio.h> #include <stdio.h>
extern int i; //extern variable void display();
int main() int n = 5; // global variable
{ int main()
printf("%d",i); {
return 0; ++n;
} display();
Output : 0 return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
Output: n=7
Storage Classes : static
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}

Output: 6 11
Storage Classes : register
#include <stdio.h>
int main()
{
register int a = 0;
printf("%u",&a);
}

Output: Compiler Error


Structure Data Type
• A structure is a user defined data type that groups logically
related data items of different data types into a single unit.

• All the elements of a structure are stored at contiguous memory


locations.

• A variable of structure type can store multiple data items of different


data types under one name.

• The data of employee in company that is name, Employee ID, salary,


address, phone number is stored in structure data type.
Defining of Structure
A structure has to be defined, before it can used. The syntax of
defining a structure is

struct <struct_name>

<data_type> <variable_name>;

<data_type> <variable_name>;

……..

<data_type> <variable_name>;

};
Example of Structure
The structure of Employee is declared as

struct
employee
{ emp_id;
name[20];
int char float char int
int salary;
}; address[50];
dept_no;
age;
Memory Space Allocation
8000 emp_id
8002 name[20]

8022 salary
8026 address[50]

8076 dept_no
8078 age
Example for sizeof() structure
#include<stdio.h>
struct stud
{
int roll;
char name[10];
int marks;
};
void main()
{
int size;
struct stud s; //Declaring a structure variable
size = sizeof(s);
printf(“\nSize of Structure : %d", size);
}
Size of Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)
= 2 + 10 + 2 = 14
Accessing a Structure Members
• The structure members cannot be directly accessed in the
expression.

• They are accessed by using the name of structure variable


followed by a dot and then the name of member variable.

• The method used to access the structure variables are


e1.emp_id, [Link], [Link], [Link], e1.dept_no,
[Link].
Initializing a Structure Members
The members of individual structure variable is initialize one
by one or in a single statement. The example to initialize a
structure variable is
1) struct student s = {111,”Sanjana”,558};

2) [Link]=111
[Link]=“Sanjana”
[Link]=558
Example program for structure Initialization
#include<stdio.h>
struct student
{
int roll;
char name[10];
float marks;
};
void main()
{
struct student s={111,"Sanjana",558};
printf("Roll no : %d\n", [Link]);
printf("Name : %s\n", [Link]);
printf("Marks : %f\n", [Link]);
}
Example program to read data from
keyboard
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;
void main()
{
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", [Link]);
printf("Enter roll number: ");
Structure Assignment
The value of one structure variable is assigned to another
variable of same type using assignment statement. If the e1
and e2 are structure variables of type employee then the
statement

e1 = e2;
assign value of structure variable e2 to e1. The value of
each member of e2 is assigned to corresponding members
of e1.
Array of Structure
The array of structure is used to store the large number of
similar records.

The syntax to define the array of structure is

struct<struct_name> <array_name> [<value>];

For Example:-
struct employee e1[100];
Program to implement the Array of
Structure
#include<stdio.h>
struct Employee scanf("%d",&Emp[i].Id);
{ printf("\n\tEnter Employee Name : ");
int Id; scanf("%s",&Emp[i].Name);
char Name[25]; printf("\n\tEnter Employee Age : ");
int Age; scanf("%d",&Emp[i].Age);
long Salary; printf("\n\tEnter Employee Salary : ");
}; scanf("%ld",&Emp[i].Salary);
void main() }
{ printf("\nDetails of Employees");
int i; for(i=0;i<3;i++)
struct Employee Emp[ 3 ]; printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Em
for(i=0;i<3;i++) p[i].Name,Emp[i].Age,Emp[i].Salary);
{ }
printf("\nEnter details of %d
Employee",i+1);
printf("\n\tEnter Employee Id
: ");
Structures within Structures

C language define a variable of structure type as a member of other


structure type. The syntax to define the structure within structure is

struct structurename1

{
data_type variable_name;
struct structurename2
{
data_type variable_name;
……..
}structure_variable2;
} structure_variable1;
Structures within Structures Example

struct employee

int empid;

char name[20];

float salary;
struct date
{ int day;
int month; int year;
}dob;
}e;
Accessing Structures within Structures

The data member of structure within structure is accessed by using


two period (.) symbol.

The syntax to access the structure within structure is


struct _var. nested_struct_var. struct_member;

For Example:-
[Link];
[Link];
[Link];
Accessing Structures within Structures
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;

void main( )
Union Data Type

• A union is a user defined data type like structure. The


union groups logically related variables into a single unit.
• The union data type allocate the space equal to space need
to hold the largest data member of union.
• The union allows different types of variable to share same
space in memory. The method to declare, use and access the
union is same as structure.
Defining of Union
A union has to defined, before it can used. The syntax of defining a
structure is

union <union_name>

<data_type> <variable_name>;

<data_type> <variable_name>;

……..

<data_type> <variable_name>;

};
Example of Union
The union of Employee is declared as

union employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
Difference between Structures &
Union
1)The memory occupied by structure variable is the sum of
sizes of all the members but memory occupied by union
variable is equal to space hold by the largest data member
of a union.
2)In the structure all the members are accessed at any point
of time but in union only one of union member can be
accessed at any given time.
Difference between Structures &
Union
Structure Union
You can use a struct keyword to define a You can use a union keyword to define a
structure. union.
Every member within structure is assigned a In union, a memory location is shared by all
unique memory location. the data members.
Changing the value of one data member will Changing the value of one data member will
not affect other data members in structure. change the value of other data members in
union.
It enables you to initialize several members at It enables you to initialize only the first
once. member of union.
The total size of the structure is the sum of the The total size of the union is the size of the
size of every data member. largest data member.
It is mainly used for storing various data It is mainly used for storing one of the many
types. data types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
Example
Example for sizeof structure and Union
#include <stdio.h>
union unionJob
{
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Example of Union
#include <stdio.h>
union Job
{
int salary;
int workerNo;
} j;
int main()
{
[Link] = 12000;
[Link] = 100;
printf("Salary = %d\n", [Link]);
printf("Number of workers = %d", [Link]);
return 0;
}
“Pointers”

58
Pointer Basics
Pointer Definition and syntax

The pointer in C language is a variable which stores the address of


another variable. This variable can be of type int, char, array, or any
other pointer.
Syntax:
Data_type *variable_name;
• Asterisk(*)is called as Indirection Operator. It is also called as
Value at Address Operator.
• It Indicates Variable declared is of Pointer type. variable_name
must follow the rules of an identifier.
Example
int *ip; //pointer to an integer
59
double *dp //pointer to double
Pointer Basics
• Normal variable stores the value whereas pointer variable stores the
address of the variable.

• The content of the C pointer always be a whole number i.e. address.

• Always C pointer is initialized to null, i.e. int *p = null.

• The value of null pointer is 0.

• & symbol is used to get the address of the variable.

• * symbol is used to get the value of the variable that the pointer is
pointing to.

• If a pointer in C is assigned to NULL, it means it is pointing to


nothing.
Pointer concept with diagrams
int i=5;
int*j;
j=&i;
Pointer Basic Example
#include <stdio.h>
void main() q ptr
{
50 5025
int *ptr, q;
q = 50; 5025 5045
ptr = &q;
printf(“Value of q =%d\t", q);
printf(“Address of q =%u\n", &q);
printf(“Address of ptr =%u\t", &ptr);
printf(“Value of ptr =%d", *ptr);
return 0;
}
OUTPUT:
Value of q = 50 Address of q = 5025
Address of ptr = 5045 Value of ptr = 50
Program on Reference and De-reference
operator
#include <stdio.h>
int main()
{
int *pc, c=22;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n",*pc);
c=11;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n",*pc);
*pc=2;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n",c);
Output
• Address of c: 26867
• Value of c: 22
• Address of pointer pc:26867
• Content of pointer pc: 22
• Address of pointer pc:26867
• Content of pointer pc: 11
• Address of c: 26867
• Value of c: 2

64
Pointer Arithmetic

Pointer Arithmetic on Integers

Pointer Expression How it is evaluated ?


ip = ip + 1 ip => ip + 1 => 1000 + 1*4 => 1004
ip++ or ++ip ip++ => ip + 1 => 1004 + 1*4 => 1008

ip = ip + 5 ip => ip + 5 => 1008 + 5*4 => 1028


ip = ip - 2 ip => ip - 2 => 1028 - 2*4 => 1020
ip-- or --ip ip => ip - 1 => 1020 - 1*4 => 1016

65
Pointer to Pointer
If a pointer holds the address of another pointer then such type of
pointer is known as pointer-to-pointer or double pointer

Syntax:

int **ptr;
66
Pointer to Pointer Example
#include<stdio.h>
void main()
{
int a, *p1, **p2;
a=65;
p1=&a;
p2=&p1;
printf("a = %d\n", a);//65
printf("address of a = %d\n", &a);//5000
printf("p1 = %d\n", p1);//5000
printf("address p1 = %d\n", &p1);//6000
printf("*p1 = %d\n", *p1);//65
printf("p2 = %d\n", p2);//6000
printf("*p2 = %d\n", *p2);//5000
67
printf("**p2 = %d\n", **p2);//65
}
Pointer to Arrays
• When an array is declared, compiler allocates sufficient amount of
memory to contain all the elements of the array.
• Base address i.e address of the first element of the array is also
allocated by the compiler.

Example:

int x[4];

From the above example,


• &x[0] is equivalent to x.
• x[0] is equivalent to *x.
Similarly,
• &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
•68 &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
Example 2: Pointers and Arrays
#include <stdio.h>
int main()
{
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
ptr = &x[2]; // ptr is assigned the address of the third element
printf("*ptr = %d \n", *ptr); // 3
printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
printf("*(ptr-1) = %d", *(ptr-1)); // 2
return 0;
}
Pointer to Structure
Accessing Structure Members with Pointer
• To access members of structure using the structure variable, we used
the dot . operator.
• But when we have a pointer of structure type, we use arrow -> to
access structure members.
Example:
struct person
{ personPtr -> age is equivalent to
int age; (*personPtr).age
float weight;
personPtr -> weight is equivalent to
}; (*personPtr).weight
int main()
{
struct person *personPtr, person1;
} 70
Pointer to Structure Example
#include <stdio.h>
struct my_structure
{
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {“Sachin", 100, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
71
return 0;
}
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.

• To define enums, the enum keyword is used.

Syntax:
enum flag {const1, const2, ..., constN};

By default, const1 is 0, const2 is 1 and so on. You can change default


values of enum elements during declaration (if necessary).
Enumeration (or enum) in C Example
#include<stdio.h> #include<stdio.h>
enum week{Mon, Tue, enum year{Jan, Feb, Mar, Apr, May,
Wed, Thur, Fri, Sat, Sun}; Jun, Jul,Aug, Sep, Oct, Nov, Dec};
int main() int main()
{ {
enum week day; int i;
day = Wed; for (i=Jan; i<=Dec; i++)
printf("%d",day); printf("%d ", i);
return 0; return 0;
} }
Output: 2 Output:
0 1 2 3 4 5 6 7 8 9 10 11
“Dynamic Memory
Allocation
and
Preprocessor Commands”

74
Dynamic Memory Allocation

The concept of dynamic memory allocation in c language enables


the C programmer to allocate memory at runtime.

Static Memory Allocation Dynamic Memory Allocation

Memory is allocated at compile Memory is allocated at run time.


time.

Memory can't be increased Memory can be increased while


while executing program. executing program.

Used in array. Used in linked list.


Dynamic Memory Allocation
Dynamic memory allocation in c language is possible by 4
functions of stdlib.h header file.

[Link]()

[Link]()

[Link]()

[Link]()
malloc()
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number
of bytes. And, it returns a pointer of void which can be casted into pointers
of any form.
Syntax of malloc()

ptr = (castType*) malloc(size);

Example
ptr = (float*) malloc(100 * sizeof(float));

The above statement allocates 400 bytes of memory. It's because the size of
float is 4 bytes. And, the pointer ptr holds the address of the first byte in the
allocated memory.

The expression results in a NULL pointer if the memory cannot be allocated


malloc() Example
#include <stdio.h>
#include <stdlib.h> printf("Enter elements: ");
void main() for(i = 0; i < n; ++i)
{ {
int n, i, *ptr, sum = 0; scanf("%d", ptr + i);
printf("Enter number of elements: sum += *(ptr + i);
"); }
scanf("%d", &n); printf("Sum = %d", sum);
ptr = (int*) malloc(n * free(ptr);
sizeof(int)); }
if(ptr == NULL)
{
printf("Error! memory not
allocated.");
exit(0);
}
calloc()
C calloc()
The name "calloc" stands for contiguous allocation.

The malloc() function allocates memory and leaves the memory


uninitialized. Whereas, the calloc() function allocates memory and
initializes all bits to zero.

Syntax of calloc()
ptr = (castType*)calloc(n, size);

Example:
ptr = (float*) calloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25


elements of type float.
calloc() Example
#include <stdio.h>
#include <stdlib.h> for(i = 0; i < n; ++i)
int main() {
{ scanf("%d", ptr + i);
int n, i, *ptr, sum = 0; sum += *(ptr + i);
printf("Enter number of }
elements: "); printf("Sum = %d", sum);
scanf("%d", &n); free(ptr);
ptr = (int*) calloc(n, sizeof(int)); return 0;
if(ptr == NULL) }
{
printf("Error! memory not
allocated.");
exit(0);
}
printf("Enter elements: ");
realloc()
C realloc()

If the dynamically allocated memory is insufficient or more than


required, you can change the size of previously allocated memory
using the realloc() function.

Syntax of realloc()

ptr = realloc(ptr, x);

Here, ptr is reallocated with a new size x.


realloc() Example
#include <stdio.h>
#include <stdlib.h> ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly
int main() allocated memory: ");
{ for(i = 0; i < n2; ++i)
int *ptr, i , n1, n2; printf("%u\n", ptr + i);
printf("Enter size: "); free(ptr);
scanf("%d", &n1); return 0;
ptr = (int*) malloc(n1 * sizeof(int)); }
printf("Addresses of previously
allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
free()

C free()

Dynamically allocated memory created with either calloc() or


malloc() doesn't get freed on their own. You must explicitly use
free() to release the space.

Syntax of free()

free(ptr);

This statement frees the space allocated in the memory pointed by


ptr.
“Preprocessor Directives”
Preprocessor Directives
C PREPROCESSOR DIRECTIVES:
• Before a C program is compiled in a compiler, source code is processed by
a program called preprocessor. This process is called preprocessing.
• Commands used in preprocessor are called preprocessor directives and they
begin with “#” symbol.
Preprocessor Directives
[Link]. Directive Description

1 #define Substitutes a preprocessor macro.

2 #include Inserts a particular header from another file.

3 #undef Undefines a preprocessor macro.

4 #ifdef Returns true if this macro is defined.

5 #ifndef Returns true if this macro is not defined.

6 #if Tests if a compile time condition is true.

7 #else The alternative for #if.


#Define and #Include Preprocessors
#define – This macro defines constant value and can be any of the basic
data types.
#include <file_name> – The source code of the file “file_name” is
included in the main C program where “#include <file_name>” is
mentioned.
Example:
#include <stdio.h>
#define height 100
#define letter 'A'
void main()
{
printf("value of height : %d \n", height );
printf("value of letter : %c \n", letter );
} Output:
value of height : 100
value of letter : A
#Define Macro With Parameter
#include <stdio.h>
#define AREA(l, b) (l * b)

int main()
{
int x = 10, y = 5, area;
area = AREA(x, y);
printf("Area of rectangle is: %d", area);
return 0;
}

Output:
Area of rectangle is: 50
#Ifdef, #Else And #Endif Preprocessors
• “#ifdef” directive checks whether particular macro is defined or not. If
it is defined, “If” clause statements are included in source file.
• Otherwise, “else” clause statements are included in source file for
compilation and execution.
Example:
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0; Output:
RAJU is defined. So, this line will be added in this C file
}
#Ifndef and #Endif Preprocessors
• #ifndef exactly acts as reverse as #ifdef directive. If particular macro
is not defined, “If” clause statements are included in source file.
• Otherwise, else clause statements are included in source file for
compilation and execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);
#endif
return 0;
Output: SELVA is not defined. So, now we are going to
define here
}
#If, #Else and #Endif Preprocessors
• “If” clause statement is included in source file if given condition is true.
• Otherwise, else clause statement is included in source file for compilation
and execution.
Example:
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since a = 100\n");
#else
printf("This line will be added in this C file since a is not equal to 100\n");
#endif
return 0;
}
Output: This line will be added in this C file
since a = 100
#Undef Preprocessor
This directive undefines existing macro in the program.
Example:
#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef & redefine:%d",height);
}
Output:
First defined value for height : 100
value of height after undef & redefine : 600
Files Introduction
A file is a container in computer storage devices used for storing data.

Need for File Handling in C:

• Reusability: It helps in preserving the data or information


generated after running the program.
• Large storage capacity: Using files, you need not worry about the
problem of storing data in bulk.
• Saves time: There are certain programs that require a lot of input
from the user. You can easily access any part of the code with the
help of certain commands.
• Portability: You can easily transfer the contents of a file from one
computer system to another without having to worry about the loss
of data.
Types of Files
There are two types of files you should know about:
[Link] files
[Link] files
1. Text files
• Text files are the normal .txt files which can be easily created using
any simple text editors such as Notepad.
• When opened, the contents are viewed as plain text which is easy to
edit.
• Takes minimum effort to maintain, are easily readable, and provide
the least security and takes bigger storage space.
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Data is stored in the binary form (0's and 1's).
• They can hold a higher amount of data, are not readable easily, and
provides better security than text files.
File Handling in C

The following operations can be performed on a file.

• Creation of a new file

• Opening an existing file

• Reading from the file

• Writing to the file

• Closing the file


Functions for file handling
SNo. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
Working with files-opening a file
• When working with files, you need to declare a pointer of type file. This
declaration is needed for communication between the file and the
program.
• We must open a file before it can be read, write, or update.
• The fopen() function is used to open a file.

FILE *fptr;
fptr = fopen ("file_name", "Mode");

• fptr is a file pointer.


• file_name is the name of the file, which you want to open. Specify the
full path here like “C:\\myfiles\\[Link]”.
• While opening a file, you need to specify the mode.
File Modes
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
Working with files-closing a file

The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.

The syntax of fclose() function is given below:

int fclose( FILE *fptr );

Or
fclose(filepointer_name);
Ex: FILE *fp;
fclose(fp);
Writing data to a file

The stdio library offers the necessary functions to write to a file:

• fputc(char, file_pointer): It writes a character to the file pointed


to by file_pointer.

• fputs(str, file_pointer): It writes a string to the file pointed to by


file_pointer.

• fprintf(file_pointer, str, variable_lists): It prints a string to the


file pointed to by file_pointer. The string can optionally include
format specifiers and a list of variables variable_lists.
Writing data to a file:fputc() function
The fputc() function is used to write a single character into file. It
outputs a character to a stream.
Syntax:
fputc(char,pointer);
Example:

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("[Link]", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
Writing data to a file:fputs() function
The fputs() function writes a line of characters into file. It outputs
string to a stream.
Syntax:
fputs(str,pointer);

Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
fp=fopen("[Link]","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
}
Writing data to a file:fprintf() function
The fprintf() function is used to write set of characters into file. It
sends formatted output to a stream.
Syntax: fprintf(pointer,str, variable);
Example:

#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("[Link]", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading data from a File
There are three different functions dedicated to reading data from a
file:
• fgetc(file_pointer): fgetc() is used to obtain input from a file single
character at a time. This function returns the number of characters
read by the function.

• fgets(buffer, n, file_pointer): It reads n-1 characters from the file


and stores the string in a buffer in which the NULL character '\0' is
appended as the last character.

• fscanf(file_pointer, conversion_specifiers, variable_adresses): It


reads characters from the file and assigns the input to a list of
variable pointers variable_adresses using conversion specifiers.
Reading data from a File:fgetc()
The fgetc() function returns a single character from the file. It gets a
character from the stream. It returns EOF at the end of file.
Syntax:
fgetc(filepointer_name);
Example:
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("[Link]","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
}
Reading data from a File:fgets()
The fgets() function reads a line of characters from file. It gets string
from a stream.
Syntax:
fgets(str,n,pointer);

Example:
#include<stdio.h>
void main()
{
FILE *fp;
char text[300];
fp=fopen("[Link]","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
}
Reading data from a File:fscanf()
The fscanf() function is used to read set of characters from file. It reads
a word from the file and returns EOF at the end of file.
Syntax:
fscanf(pointer, conversion specifier, variable);
Example:

#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("[Link]", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Writing and Reading to a binary file
Writing to a binary file:
To write into a binary file, you need to use the fwrite() function. The
functions take four arguments:
• address of data to be written in the disk
• size of data to be written in the disk
• number of such type of data
• pointer to the file where you want to write.

Syntax:
fwrite(addressData, sizeData, numbersData, pointerToFile);

Reading from a binary file:


Function fread() also take 4 arguments similar to the fwrite() function.
Syntax:
fread(addressData, sizeData, numbersData, pointerToFile);
Writing to a binary file:Example
#include <stdio.h> int main()
#include <stdlib.h> {
struct threeNum int n;
{ struct threeNum num;
int n1, n2, n3; FILE *fptr;
}; if ((fptr = fopen("[Link]","wb")) == NULL){
printf("Error! opening file");
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr); }
Reading from a binary file:Example
#include <stdio.h> void main()
#include <stdlib.h> {
struct threeNum int n;
{ struct threeNum num;
int n1, n2, n3; FILE *fptr;
}; if ((fptr = fopen("[Link]","rb")) == NULL){
printf("Error! opening file");
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1,
num.n2, num.n3);
}
fclose(fptr);
}
Random Access Functions: fseek()
fseek() function is used to move file pointer position to the given
location.
Syntax:
int fseek(FILE *stream, long int offset, int whence)

Parameters
stream - This is the pointer to a FILE object that identifies the stream.
offset - This is the number of bytes to offset from whence.
whence - This is the position from where offset is added.
It is specified by one of the following constants.

Constant Name Constant Value Description


SEEK_SET 0 The begining of file
SEEK_CUR 1 The current position in file
SEEK_END 2 The end of file
Random Access Functions: fseek()
Example:
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("[Link]","w+");
fputs("This is MRECW", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}

O/p:
This is C Programming Language
Random Access Functions: ftell()
ftell() function returns the value of the current pointer position in the
file. The value is count from the beginning of the file.
Syntax: ftell(fptr);
Example:

#include<stdio.h>
int main()
{
FILE *fp = fopen("[Link]","r");
char string[20];
fscanf(fp,"%s",string);
/* Printing position of file pointer */
printf("%ld", ftell(fp));
return 0;
}
Random Access Functions: rewind()
rewind() function is used to move the file pointer to the beginning of the
given file.
Syntax: rewind( fptr);
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("[Link]","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
}
Appending data to existing files
#include <stdio.h>
#include<stdlib.h>

int main()
{
FILE *fp;
fp= fopen("[Link]", "a"); // Open the file in append mode

// Check if the file was successfully opened


if (fp== NULL)
{
printf(“ file does not exist !\n");
exit(0);
}

fprintf(fp, "C Programming Language \n"); // write to the file

fclose(fp); //close the file

return 0;
}

You might also like