[go: up one dir, main page]

0% found this document useful (0 votes)
16 views135 pages

PPS - Unit 3

Uploaded by

mrecwcse.b.5b6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views135 pages

PPS - Unit 3

Uploaded by

mrecwcse.b.5b6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 135

UNIT-III

UNIT – III

Functions: Declaring a function, Parameters and return type of a function,


passing parameters to functions, Recursive Functions, Storage Classes.
Structures: Defining structures, initializing structures, unions.
Pointers: Idea of pointers, Defining pointers, Pointer to Pointer, Dynamic
Memory Management functions (DMA)
File Handling in C: Creating and Reading and writing text and binary
files, Appending data to existing files, Writing and reading structures
using binary files, Random access using fseek, ftell and rewind functions.

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:
1.Library Functions: are the functions which are declared in the C
header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2.User-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>
#include<conio.h>
void addition() ; // function declaration
void main()
{
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 no argument but returns a value
Function with no argument but returns a value
#include<stdio.h>
#include<conio.h>
int addition() ; // function declaration
void main(){
int result ;
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 argument but no return value
Function with argument but no return value
#include<stdio.h>
#include<conio.h>
void addition(int, int) ; // function declaration
void main(){
int num1, num2 ;
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 ) ;
}
Function with argument and returns a value
Function with argument and returns a value
#include<stdio.h>
#include<conio.h>
int addition(int, int) ; // function declaration
void main(){
int num1, num2, result ;
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) ;
}
Passing Parameters to Functions
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...

Call by Value
Call by Reference
Call 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,int) ; // function declaration
void main(){
int num1, num2 ;
num1 = 10 ; num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Call 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 *,int *) ; // function declaration
void main(){
int num1, num2 ;
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);
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
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()


ctype.h data values
Recursion
A function that calls itself is known as a recursive function.
Recursion Example
#include<stdio.h>
int factorial( int ) ;
void main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("\nFactorial of %d is %d\n", n, fact) ;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
return n * factorial( n-1 ) ; // recursive function call
}
Program: Output:
// C program to calculate sum of digits using recursion
#include <stdio.h>
int sumOfDigits(int num);
void main()
{
int num, sum;
clrscr();
printf("Enter any number to find sum of digits: ");
scanf("%d", &num);
sum = sumOfDigits(num);
printf("Sum of digits of %d = %d", num, sum);
getch();
}
// Recursive function to find sum of digits of a number
int sumOfDigits(int num)
{
if(num == 0)
return 0;
return ((num % 10) + sumOfDigits(num / 10));
}
Program:
// Sum of Natural Numbers Using Recursion Output:
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
clrscr();
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
getch();
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
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.
•Recursion uses more processor time.
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>
int a=7; // a is a global variable #include "scope_pg.c"
void fun() void fun();
{ void main()
a++; {
printf("Program without main():%d",a); // 8 extern int a;
} clrscr();
printf(“a=%d\n”,a); // 7
fun();
printf(“a=%d”,a); // 8
getch();
}
Output:
7
Program without main(): 8
8
Storage Classes : static
Program: Program:
#include <stdio.h> #include <stdio.h>
void demo() void main()
{ {
// static variable int i;
static int count = 0; clrscr();
printf("%d\t",count); for(i=0;i<5;i++)
count++; {
} int count = 0;
void main() printf("%d\t",count);
{ } count++;
Output: Output:
int i; }
01234 00000
clrscr(); getch();
for (i=0; i<5; i++) }
demo();
getch();
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 a 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
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int 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)
Accessing 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, e1.name, e1.salary, e1.address, e1.dept_no, e1.age.
Accessing 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, e1.name, e1.salary, e1.address, e1.dept_no, e1.age.
Initializing Structure Members
The members of individual structure variable is initialized one by
one or in a single statement. The example to initialize a structure
variable is
1) struct student s = {111,”Sanjana”,558};

2) s.rollno=111;
strcpy(s.name,“Sanjana”);
s.marks=558;
Example program for structure Initialization
#include<stdio.h>
struct stud
{
int roll;
char name[10];
int marks;
};
void main()
{
int size;
struct stud s={111,"Sanjana",558};
printf("Roll no : %d\n", s.roll);
printf("Name : %s\n", s.name);
printf("Marks : %d\n", s.marks);
}
Example program to read data from keyboard
• #include <stdio.h> •
• struct student
• { • scanf("%d", &s.roll);
• char name[50]; • printf("Enter marks: ");
• int roll; • scanf("%f", &s.marks);
• float marks; • printf("Displaying Information:\
• } s; n");
• void main() • printf("Name: ");
• { • puts(s.name);
• printf("Enter information:\n"); • printf("Roll number: %d\
n",s.roll);
• printf("Enter name: ");
• printf("Marks: %f\n", s.marks);
• scanf("%s", s.name);
• }
• 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
for(i=0;i<3;i++) %ld",Emp[i].Id,Emp[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 <struct_name>

{
<data_type> <variable_name>;
struct <struct_name>
{
<data_type> <variable_name>;
……..
}<struct_variable>;
} <variable_name>;
Structures within Structures Example

The structure of Employee is declared as

struct employee

int emp_id; char name[20]; float salary;


int dept_no;
struct date
{
int day;
int month; int
year;
}doj;
}e1;
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:-
e1.doj.day;
e1.doj.month;
e1.doj.year;
Accessing Structures within Structures
#include <stdio.h> {
#include <string.h> e1.id=101;
struct Employee strcpy(e1.name, "Sonoo
{ Jaiswal");//copying string into char array
int id; e1.doj.dd=10;
char name[20]; e1.doj.mm=11;
struct Date e1.doj.yyyy=2014;
{ printf( "employee id : %d\n", e1.id);
int dd; printf( "employee name : %s\n",
int mm; e1.name);
int yyyy; printf( "employee date of joining
}doj; (dd/mm/yyyy) : %d/%d/%d\n",
}e1; e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
}

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 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
We can use a struct keyword to define a We 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 us to initialize several members at It enables us to initialize only the first member
once. 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.
We can retrieve any member at a time. We can access one member at a time in the
union.
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()
{
j.salary = 12000;
j.workerNo = 100;
printf("Salary = %d\n", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
“Pointers”

61
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
62 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);
return 0;
}
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

67
Pointer compatability
Example:
int x=9,*ptr1;
float y=5.55,*ptr2;
char ch='a',*ptr3;
ptr1=&x; // Correct, because ptr1 and x belong to same type of data(int).
ptr2=&x; // Incorrect, because ptr2 and x belong to different types of data.
ptr3=&x; // Incorrect, because ptr3 and x belong to different types of data.
ptr1=&y; // Incorrect, because ptr1 and y belong to different types of data.
ptr2=&y; // Correct, because ptr2 and y belong to same type of data(float).
ptr3=&y; // Incorrect, because ptr3 and y belong to different types of data.
ptr1=&ch; // Incorrect, because ptr1 and ch belong to different types of data.
ptr2=&ch; // Incorrect, because ptr2 and ch belong to different types of data.
ptr3=&ch; // Correct, because ptr3 and ch belong to same type of data(ch).
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

69
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;
70
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
71
printf("**p2 = %d\n", **p2);//65
}
Void pointer
A void pointer points to unknown datatypes.
A void pointer doesnot know to which data it is pointing to.
Void pointer is a specific pointer type – void * – a pointer that points to
some data location in storage, which doesn’t have any specific type.
Program:
#include<stdio.h>
int x;
float y;
char ch;
void *ptr=&x; // void pointer
void main()
{
clrscr();
*(int*)ptr=15; // int* is called as pointer type casting
printf("x:%d\n",x);
ptr=&y;
*(float*)ptr=5.55;
printf("y:%f\n",y);
ptr=&ch;
*(char*)ptr='s';
printf("a:%c",ch);
getch();
}
// (float)--->normal type casting
// (*float)--->pointer type casting
Output:
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).
•74 &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
Example 1: Pointers and Arrays
#include <stdio.h>
int main()
{
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i)
{
scanf("%d", x+i); // Equivalent to scanf("%d", &x[i]);
sum += *(x+i); // Equivalent to sum += x[i]
}
printf("Sum = %d", sum);
return 0;
}

The program computes the sum of six elements entered by the user.
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;
}
Pointers as Function Argument in C
• Pointer as a function parameter is used to hold addresses of
arguments passed during function call. This is also known as call
by reference.
• When a function is called by reference any change made to the
reference variable will effect the original variable.

• The address of num1 and num2 are passed to the swap() function
using swap(&num1, &num2);.

• Pointers n1 and n2 accept these arguments in the function


definition.
void swap(int* n1, int* n2)
{
... ..
}77
Call by value vs Call by reference
Call by Value Example
#include<stdio.h> Output:
void adc(int x,int y);
void main()
{
int x=4,y=5;
clrscr();
dc(x,y);
printf("Inside main function after call:\n x=%d\ty=%d",x,y); // x=4 y=5
getch();
}
void dc(int x,int y)
{
x++;
y--;
printf("Function definition:\n x=%d\ty=%d\n",x,y);
}
Call by Reference Example
#include<stdio.h> Output:
void uc(int *x,int *y);
void main()
{
int x,y;
clrscr();
uc(&x,&y);
printf("Inside main function after call:\n x=%d\ty=%d",x,y);
getch();
}
void uc(int *x,int *y)
{
*x=4;
*y=5;
printf("Function
80 definition:\n x=%d\ty=%d\n",*x,*y);
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;
} 81
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);
82
return 0;
}
Self Referential Structure
Self Referential structures are those structures that have one or
more pointers which point to the same type of structure, as their
member.

In other words, structures pointing to the same type of structures are


self-referential in nature.
83
Self Referential Structure Example
void main()
#include<stdio.h>
{
struct node {
struct node ob1;
int data1;
ob1.link = NULL;
char data2;
ob1.data1 = 10;
struct node* link;
ob1.data2 = 20;
};
struct node ob2;
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
ob1.link = &ob2; // Linking ob1 and ob2
/*Accessing data members of ob2 using
ob1*/
printf("%d", ob1.link->data1);
84 printf("\n%d", ob1.link->data2);
}
“Dynamic Memory
Allocation
and
Preprocessor Commands”
85
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.

1.malloc()

2.calloc()

3.realloc()

4.free()
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
Sr.No. 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.

8 #elif #else and #if in one statement.

9 #endif Ends preprocessor conditional.


#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
“Command Line Arguments”
Command Line Arguments
• The arguments passed from command line are called command line
arguments. These arguments are handled by main() function.
• The argument values are passed on to your program during
program execution.

Syntax:
int main(int argc, char *argv[])

Where,
1.argc: It refers to “argument count”. It counts the number of
arguments on the command line.

2.agrv: It refers to “argument vector”. It is basically an array of


character pointer which we use to list all the command line arguments.
Command Line Arguments Example
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char * argv[])
{
int i, sum = 0;
if (argc != 3)
{
printf("You have forgot to specify two numbers.");
exit(1);
}
printf("The sum is : ");
sum= atoi(argv[1])+atoi(argv[2]);
printf(“Sum=%d", sum); Output:
return 0; cmd1.exe 10 20
} Sum=30
Command Line Arguments Execution
1. Open Turbo C++.

2. Write a program.

3. Compile and Run your program.It produces the


following result:

“You have forgot to specify two numbers.”

4. Open DOS Shell.


Command Line Arguments Execution
4. Open DOS Shell.
Command Line Arguments Execution
5. Change directory
Now you need to change the current directory of DOS Shell to
"SOURCES" from "BIN", for this you need to user cd command.

First use cd.. for coming back to Turbo C++ main directory

cd..

Now use cd SOURCE to access the SOURCE directory

cd SOURCE
Command Line Arguments Execution
6. Execute Program with Command Line Arguments
FILES

UNIT – III
Functions: Declaring a function, Parameters and return type
of a function, passing parameters to functions, Recursive
Functions, Storage Classes.
Structures: Defining structures, initializing structures,
unions.
Pointers: Idea of pointers, Defining pointers, Pointer to
Pointer, Dynamic Memory Management functions (DMA)
File Handling in C: Creating and Reading and writing text
and binary files, Appending data to existing files, Writing
and reading structures using binary files, Random access
using fseek, ftell and rewind functions.
111
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:
1.Text files
2.Binary 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\\newfile.txt”.
• 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 );


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:
int fputc(int c, FILE *stream);

Example:

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("file1.txt", "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:
int fputs(const char *s, FILE *stream);

Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
fp=fopen("myfile2.txt","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:
int fprintf(FILE *stream, const char *format [, argument, ...])

Example:

#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("file.txt", "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:
int fgetc(FILE *stream);
Example:
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("myfile.txt","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:
char* fgets(char *s, int n, FILE *stream);

Example:
#include<stdio.h>
void main()
{
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","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:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:

#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "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("program1.bin","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("program.bin","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("file.txt","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("test.txt","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("file.txt","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> printf("1 file created...\n");
int main() getchar();
{ printf("\nThe contents of file
FILE *p; are..");
char fname[20],ch; rewind(p);
printf("Enter the file name:"); while(1)
scanf("%s",fname); {
p=fopen(fname,"a+"); ch=fgetc(p);
while(1) if(ch==-1)
{ break;
ch=getchar(); printf("%c",ch);
if(ch==-1) }
break; fclose(p);
fputc(ch,p); }
}
“Thank You”

135

You might also like