0% found this document useful (0 votes)
3 views

Array

The document provides an overview of arrays, functions, pointers, and dynamic memory allocation in C programming. It explains the syntax for declaring and initializing arrays and pointers, demonstrates call by value and call by reference, and discusses pointer arithmetic and relationships between arrays and pointers. Additionally, it covers dynamic memory management functions like malloc, calloc, and realloc, along with examples of their usage.

Uploaded by

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

Array

The document provides an overview of arrays, functions, pointers, and dynamic memory allocation in C programming. It explains the syntax for declaring and initializing arrays and pointers, demonstrates call by value and call by reference, and discusses pointer arithmetic and relationships between arrays and pointers. Additionally, it covers dynamic memory management functions like malloc, calloc, and realloc, along with examples of their usage.

Uploaded by

Ritika Choudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 130

Array :

Similar data item stored in


contiguous memory location
Syntax.
Syntax:
Data_type array_name[Size]
Eg: int a[10];
Int a[5]={1,2,3,4,5,6}
For(i=0;i<5;i++)
A[2]=3
Function:
It take one or more argument
(value) and return singlr result
1) Call by value
2) Call by reference
1) call by value :
/*swapping concept */
Int main()
{
Int a=3,b=2;
Prinft(“%d %d before
swapping”,a,b);
Swap(a,b);
Printf(“after swap%d
%d”,a,b);
Return 0;
}
Void swap(int x,int y)
{
Int temp;
Temp=x;
X=Y
Y=temp;
}

Call by reference
/*swapping concept */
Int main()
{
Int a=3,b=2;
Prinft(“%d %d before
swapping”,a,b);
Swap(&a,&b);
Printf(“after swap%d
%d”,a,b);
Return 0;
}
Void swap(int *x,int *y)
{
Int temp;
Temp=*x;
*X=*Y
*Y=temp;
}
Array and function
Passing array to function
Passing an array to a
function allow the function
to directly access and
modify the original array

Int main()
{
Int age[]={1,2,3,4,5};
Printarray(a,5);
Return 0;
}

Void printarray(int a[],int n)


For(i=0;i<n;i++)
{
Print(%d”,a[i]);
3/03/2025
____________________________
_
Pointer :
It is variable that stored the
address of another .
Int a=5;

Declaration of pointer

Syntax: data_type
*p_name;
Eg:
Int *p,*q;
Char *str;
Float *base;
Initialization of pointer

& used to determine the


address of the variable
Syntax:
<pointer declaration>
Pointer_name=&variable<address of
variable>

Eg: int *a,n;


A=&n;

// program for pointer


declaration and
initialization
#include <stdio.h>
Int main()
{
Int *ptr,n=2; //pointer declaration
Ptr=&n;
Printf(“addr of varible
%x,&n);

Printf(“value of pointer
%d,*ptr);
Return 0;
}

Output:
Addr of varible fff4
Value of pointer 2

Dereferencing of pointer
 it is used to perform access
or manipulate data
contained in memory
location pointed to by a
pointer
eg:
int num=50,x;
int *ptr;
ptr=&num;
x=*ptr;

num=50
&num= 1002
Ptr=1002
*ptr=50

// Dereferencing operator using


pointer
Int main()
{
Int *pc ,c;
C=22;
Printf(“Address of c”,&c);
Printf(“value of c %d”,c);
Pc=&c;
Printf(“addr of pc %x,&pc);
Printf(“value of pc%d”,*pc);
Return 0;
}
Pointer Arithmetic
1) increment (++) or
Decrement operator (--)
2) addition and subtraction (+
and -)
3) comparison of two
operators
4) differencing pointer or
subtraction of one pointer
from another
1) increment and decrement
of pointer :

eg: int a=20,*ptr;


ptr=&a;
ptr ++;
ptr--;
/*Program for increment the
variable pointer to access each
succeeding element of the
array
Int main()
{
Int a[]={20,200,300};
Int i, *ptr;
Ptr=a;
For(i=0;i<3;i++)
{
Printf(“addr of a[%d]=
%x”,I,ptr);
Printr(“value of a[%d]=
%d,*ptr);
Ptr++;
}
Return 0;
}

Output
Addr of a[0]=fff0
Value of a[0]=20
Addr of a[1]=fff2
Value of a[1]=200
Addr of a[2]=fff4
Value of a[2]=300
Addition and subtraction:
Syntax:
Finalvalue=(addr)+(const no
*size of datatype)
Eg: int *ptr,n;
Ptr=&n;
Ptr=ptr+3;
Ptr=ptr-3;
Ptr=1000+3*2
=1000+6
=1006
Ptr=1000-3*2
=1000-6
=994
/* Addition value to pointer
value*/

Int main()
{
Int no=5,*ptr;
Ptr=&no;
Printf(“addr of pointer
%x”,ptr);
Ptr=ptr+3;
Printf(after additing 3 :addr of
pointer is %x”,ptr);
Return 0;
}
Output:
Addr of pinter 1000
After adding 3: addr of pinter
is :1006

Comparison between pointer

<, > ,<= ,>= ,== ,!=


Int main()
{
Int
num[10]={1,2,4,5,6,7,8,9,0},*a
,*b,*c;
a=&num[2];
b=num+2;
c=&num[6];
printf(“addr a=%x b=%x c=
%x”,a,b,c)
if(a==b)
printf(“a and b point to same
location and its value%d”,*a);
if(a!=c)
printf(“a and c not point to
same location”,*a,*c);
return 0
}

Output
A=1000
B=1000
C=3000
A and b is same location
value :
A and c is not in same location:
Relationship Between Array and
Pointer
#include<stdio.h>
Int main()
{
Int a[5]={1,3,2,4,6},I;
For(i=0;i<5:i++)
{
Printf(“value of a[%d]=
%d”, I,a[i]);
Printf(“addr of a[%d]=
%x”,I ,&a[i]);
}
}
Two way to show relationship
between pointer and aaray
a) pointer to array
b) array to pointer
a) pointer to array:
syntax:
datatype (*varname)
[size]

# include <stdio.h>
Int main()
{
Int *p;
Int(*ptr)[5]; // point to array
Int a[5];
P=a
Ptr=&a;
Prinf(“p=%x ptr=%x”,p,ptr)
P++;
Ptr++;
Printf(“p=%x ptr=
%x”,p,ptr );
Return 0;
}

___________________________-
Array of point

Syntax: datatype
*array_name[size]

Eg: int *array_ptr[50]

//
#include<stdio.h>
Int main()
{
Int *arrop[3]
Int a=10,b=20,c=30,I;
Arrop[0]=&a
Arrop[1]=&b;
Arrayop[2]=&c;
(i=0;i<3;i++)
{
Printf(”addr =%x
value=%d”
arrop[i],*arrop[i]);
}
Return 0;
}
Int arr[]={3,5,4,3,2}
Int *p=arr;
Int(*ptr)[5]=&arr;
Printf(“p=%x ptr=%d”,p, *ptr);
Return 0;
}
…………………………………………
……
Double pointer:
Pointer to pointer
The difference between pointer
and pointer to pointer is we
have to place an additional “*”
before the name of pointer
Syntax: int **p ;

*p=10
**p=10

Int main()
{
Int a=20;
Int *ptr2;
Int **ptr1;
Ptr2=&a;
Ptr=&ptr2;
Printf(“ value of a=%d”,a);
Printf(“value using single
pointer=%d”,*ptr2);
Printf(“value using double
pointer=%d”,**ptr1);
Return 0;
}

Function and pointer


A=10 +100 A=110
Int main()
{
Int x=10
// Void change(int *num);
Change(&x);
Printf(“after function call x=
%d”,x);
Return 0;
}
Void change (int *num)
{
*num=*num+100;
}

Call by value call by


reference

Returning pointer from function


A function can return pointer to
calling function
Return_type
*function_name(arug_list)
Eg:
Int *f(char a[8]);
Char *f1(int *p,int *q)

/* find the max of two no */


#

Main()
{
Int *max(int *p ,int *q);
Int a,b,*m;
Printf(“enter two no”);
Scanf(%D%D” &a,&b);
M=max(&a,&b);
Printf(max value %D, *m)
}
Int *max(int *p,int *q)
{
If(*P>*q)
Return p;
Else
Return q;}
Dynamic Memory allocation
Two types of DMA
1)compile time (static)
2) dynamic memory
allocation(run-time)
<stdlib.h>
Or
<malloc.h>
------------------------------------
a) malloc()
void malloc(number
*sizeof(int));
function is used for
allocates
b) calloc()
void calloc(number,
sizeof(int));
calling to elements

c) realloc()
void realloc
(pointer_name,number
*sizeof(int));
reallocates mempry
extending it up to newsize
d) free()
free(pointer_name);

Dynamic memory
management/allocation

Int a[8]
A[0 A[1 A[2 A[3 A[4 A[5 A[6 A[7
] ] ] ] ] ] ] ]
7 8 1 4

Solution is DMA
Functions DMA
1)malloc():
Syntax: ptr=(datatype*)
malloc(size)
Eg: int p*
P=(int*) mallaoc(20);
Or
P=(int*)
malloac(n*size(int));
Eg:
#include<stdio.h>
#include<stdlib.h>

Void main()
{
Int *p,n,i;
Prinf(“enter the value of
n”);
Scanf(“%d”,&n);
P =(int *) malloc(n*2);
Printf(“ enter the integer”):
For(i=0;i<n;i++)
{
Scanf(“%d”, p+1);
}
Free(p);
}
Calloc()

Ptr=(datatype*)calloc
(n,size)
Eg:
Int *P;
P=(int*) calloc(10,2)
Or
P=(int*) calloc(n,size(int));
Eg:
Void main()
{
Int *p,n,i;
Prinf(“enter the value of
n”);
Scanf(“%d”,&n);
P =(int *) calloc(n,2);
Printf(“ enter the integer”):
For(i=0;i<n;i++)
{
Scanf(“%d”, p+1);
}
Free(p);
}
-------------------------------------
=--
Realloc()
Syntax:
Ptr=(datatype*)
realloc(ptr,newsize);
Eg:
P=(int*)malloc(10*2);
P=(int*)realloc(p,20);
Eg:
Void main()
{
Int *p,n,i;
Prinf(“enter the value of
n”);
Scanf(“%d”,&n);
P =(int *) malloc(2);
P=(int*)realloc(p,n);
Printf(“ enter the integer”):
For(i=0;i<n;i++)
{
Scanf(“%d”, p+1);
}
Free(p);
}

Free()
P=(int*) malloc(10);
Free(p);
Types of pointer
1) NULL pointer
2) Dangling pointer
3) Wild pointer
4) Near pointer
5) Far pointer
6) Huge pointer
_____________________________
1) NULL pointer : pointer
which is initialized with
NULL value
#include<stdio.h>
Int main()
{
Int *ptr= NULL;
Printf(“the value of ptr
%x”,ptr);
Return 0; }
Dangling pointer
Is a pointer that’s points to the
memory even after its
deallocation.
Void pointer /generic pointer
Void pointer does not have any
data type associated with it .
It contain address of any type
of variable
Eg:
Char ch=’a’;
Void *p;
P=&ch
Printf(“%c,ch);
Wild pointer
A wild pointer points to some
random memory location.
Near pointer
This pointer points only 64kb
data segment
________________________________
__ffar pointer
The pointer which can point or
access whole the residence
memory
Size of far pointer is 4 bytes or
32 bits
Int far *ptr;

Huge pointer
Sillary far pointer
Char huge *p;
________________________________
_-
1) Swap two no using pointer
and function
2) To input element in an array
and reverse the array using
pointer
3) Sort an array using pointer
4) Find length of the srring .

Int main()
{
Int n,I,a[15];
Int *p;
Printf(“input the no of
element “);
Scanf(“%d”,&n);
P=&a[0];
Printf(“enter the
elements”);
For(i=0;i<n;i++)
{
Printf(“%d” ,i+1)
Scanf(“%d,p);
P++;
}
P=&a[n-1];
Printf(“reverse order”);
For(i=n;i>0;i--)
{
Printf(“ %d %d “,I,*p)
p--;
}
Return 0;
}

Sort an array using pointer

2 5 3 7 1==== 1 2 3 5 7
A[0]>a[1]
2>5 no
A[0]>a[2]
2>3 no
A[0]>a[3]
2>7 no
A[0]>a[4] true
(a)2>1(b)
t=a
a=b
b=t
int main()
{
Int *a,i,j,temp,n;
Printf(“enter the no of
elemrnt”);
Scanf(“%d”,&n);
For(i=0;i<n;i++)
{
Printf(“%d”,i+1);
Scanf(“%d”,a+i);
}
For(i=0;i<n;i++) a[0]
{
For(j=i+1 ; j<n;j++)
a[1]
{
a b
If (*(a+i)>*(a+j))

{ a=*(a+
i)

B=*(a+j)
Temp=*(a+i);
temp=a
*(a+i)=*(a+j)
a=b
*(a+j)=temp
b=temp
}
Printf(“sorted array”);
For(i=0;i<n;i++)
{

printf(“%d %d “,i+1,*(a+i));
}
Print(“\n);
Return 0;
}
Strings:
String “”=double quotes \
0=null character
“Abcds”

String Literal/string constant


Def :
Is a sequence of characters
enclosed in double qutoes and
terminated by null character \0.
“A”
“1234”

Declaration of string
Syntax :
Char string_name[size];
Eg:

Char city[30];
Char name[20];

Definition of string:

Eg:
India
I N D I A \0
Initialization of string

1) Char greeting[6] =
{ ‘H’,’e’,’l’,’l’,’o’,\0};
2) Char greeting[6]= “hello”;
3) Char greeting[]=”Hello”;
4) Char *ptr =” pune”;
// program to print characters
of a string and address of each
character

#include<stdio.h>
Int main()
{
Char str[]=”India”;
Int i;
For(i=0; str[i]!=’\0’; i++)
{
Printf(“ character =
%c”,str[i]);
Printf(“address=%x”, &str[i]);
}
Return 0;
}

Print the address and


char of the string using pointer

#
Int main()
{
Char str[]=”india”;
Char *p;
P=str;
While(*p!= ‘\0’)
{
Printf(“ character=%c”, *p);
Printf (“Address=%x”,&p);
P++;
}Return 0;}
Accepting and displaying of
String
Char c[20];
Scanf(“%s”,c);

// program for scanf() function


#
Int main()
{
Char name[20];
Printf(“ enter the string”);
Scanf(“%s”,name);
Printf(“%s”,name);
Return 0;
}

________________________________
__Scanf() & gets()
Printf() & put()

Gets()
It is used to read character
from the standard input and
stores them as a string until a
new line character or end of file
is reached
#include<stdio.h>
Int main()
{
Char name[20];
Printf (“enter the name”);
Gets(name);
Return 0;
}
Printf()
To print a string we can either
use printf with %s formate or
put()

#
Int main()
{
Char str[10];
Prinf(“enter the string”);
Scanf(“%s”,str);
Printf(“ string is =%s”,str);
Return 0;
}
Put ()
Writes the string out to
standard output

Syntax:
Puts(char *str);
// puts()
Int main()
{
Char string[] =” this is an
exam”;
Puts(string);
Puts (“string”);
Return 0;
}

Predefined string function

1) Strlen() ;
To find length of the string

Syntax:
Int strlen(const char *str)

// strlen()
#include <stdio.h>
#include<string.h>
Int main()
{
Char a[20] =”program”;
Printf(“ length of string
a=%d”,strlen(a));
Return 0;
}
2) Strcmp()
It campares two strings
Syntax:
Int strcmp(const char
*str1,const char *str2)

0 If both
strings are
equal
Negative If value of
first
unmatched
char is less
than second
Positive If value of 1st
unmatched
char is
greater than
2nd

// stricmp()
#
#
Int main()
{
Char str1[]=”
abcd” ,str2[]=”aBcd”
Int result;
Result=strcmp(str1,str2);
Printf(“result = %d”, result);
Return 0;
}

Strncmp()

Compares first n character


of string s1 to s2
Syntax:
Int strncmp(const char
*s1,const char *s2, int n)

0 S1 s2 are
equal
>0 1st unmatch
character of
s1 is greater
than s2
<0 First unmatch
char s1 is
less than s2

// program for strncmp()


#
#
Int main()
{
Char s1[20];
Char s2[20];
Strcpy(s1,”hello”);
Strcpy(s2,”hello class”);
Result=strncmp(s1,s2,3)
If(result>0)
Printf(“ first unmatched
character of s1 is greater than
s2);
Else if(result <0)
Printf(“first unmatched
character of s1 is less than
s2”);
Else
Printf(“both the strings are
equal”);
Return 0;
}

Strcpy()
Copies the string to the another
character array.
Char * strcpy(char*
destination,char char *source)

// program for strycpy()


#
#
Int main()
{
Char s1[10]=”pune”
Char s2[10];
Char s3[10];
Strcpy(s2,s1);
Strcpy(s3,”well”);
Puts(s2);
Puts(s3);
Return 0;
}
Strncpy()

Syntax Char * strcpy(char*


destination,char char
*source,int n )

// program for strncpy


#
#
Int main()
{
Char s[]=”FYBBA CA”
Char t[20]=””;
Printf(“%s”,s);
Printf(“%s”,t);
Strncpy(t,s,5);
printf(“%s”, t);
return 0; }
strcat()

syntax
char * strcat(char
*destination,const char *
source);
//strcat
#
#
Int main()
{
Char s1[]=” this is
“,s2=”program”;
Strcat(s1,s2);
Puts(s1);
Puts(s2);
Return 0; }
String
Command line Arguments
CLA are arguments passed to
main() function during run time
fromfrom command line ;

“ the argument passed through


the main() function are called
CLA.”
Syntax:
Int main(int argc , char
*argv[])
Or
Int main(int argc , char
**argv[])

Argc =5
Argv[0]
Argv[1]
Argv[2]
Argv[3]
Argv[4]

Argc =argument count


Is int and stores number of
command line aruments
passed ny user
____________________________
Argv= argument vector
Is array of character pointers
listing all the arguments .

Properties
1) It passed to main()
function .
2) Argument supplied at the
run time
3) They are used to control
the program from outside
4) Argv[argc] is NULL
pointer
5) Argv[0] hold the name of
the program
6) Argv[1] point to first cLA
// program for command line
argument

#include<stdio.h>
Int main (int argc ,char *argv[])
{
Printf(“%s” argv[0]);
If(argc==2)
{
Prinft (“%s”,argv[1]);
Elseif(argc>2)
Printf(“to mant argument
supplied “);
Ekse
Printf(“onr argument expected
“);
Return 0;
}

Structures and Union


Concept of structure
1) Definition
2) A structure helps to gather
different typres of
information that comparise
a given entity .
3) It’s a tool for handling a
group of logically related
data item.
4) A structure is a collection of
variables under a single
name

Definition
A structure is a collection of
one or more varoibale
possibly of different data
types group together under
single name

Syntax:
Struct tag_name
{
Datatype member 1;
Datatype member 2;
Datatype member n;
} [one or more structure
varibles];

Declaring Structure variable

Struct student
{
Char name[20];
Int roll_no;
Float marks;
};

Declaring structure variable


Two way
1) With structure definition
2) Using structure tag
Syntax:
Struct structure_name
structure_variable ;

1)
Struct date
{
Int date ;
Char month[20];
Int year ;
} today;
Struct student
{
Char name[20];
Int roll_no;
Float marks;
} s1,s2;
Tag name;
Struct date
{
int date;
Char month[20];
Int year;
}
Struct date today ;

Struct student
{
Char name[20];
Int roll_no;
Float marks ;
}Struct student s1,s2;
Initialization of structure
variable
Syntax:
Struct tag
variable={ member_value
separated by comma};

Eg:
Struct student
{
Char name[20];
Int roll_no ;
Float avg;
} s1={ “soham”,10,87.8};
Struct student
{
Char name[20];
Int roll_no;
Float avg;
}
Sturct student
s1={“rohit”,20,89.4};

typedef
syntax

typedef old_type new_type;


typedef struct
{
Datatype mem1;
Datatype mem 2;
……
Datatype mem n;
} new_type;

Eg:
Typedef struct
{
Char ename[20];
Int sal;
Int deptno;
} employee;
Accessing structure members

Syntax:

Structure_variable_name.struct
ure_member_name
Struct student
{
Char name[20]l;
Int roll_no;
Float avg;
} s1={“soham”,10,87.9};

S1.name
S1.roll_no
S1.avg
/* program for accept and
display student information

# include<stdio.h>
Struct student
{
Char name[20];
Int roll_no;
Flat marks;
} s;
Int main()
{
Printf(“enter information”);
Printf(“enter name”);
Scanf(“%s”,&s.name);
Printf(“enter roll no”);
Scanf(“%d”, &s.roll_no);
Printf(“enter marks”);
Scanf(“%f”, &s.marks);
Printf(“display information”);
Puts(s.name);
Printf(“%d”,s.roll_no);
Printf(“%f”,s.marks);
Return 0;
}

Nested structure
A structure includes another
structure is called nested
structure

Syntax:
Struct tag_name 1
{
Datatype member1 ;
Dattype member2;
……
};
Struct tag_name2
{
Datatype member1;
….
Struct tag_name1 var;
….
};
Example :
Struct subject
{
Char subname[30];
Int marks;
};
Struct stud_res
{
Int rollno;
Char name[20];
Char std[20];
Struct subject subj;
} result;

// program for nested structure


Struct stud_res
{
Int rno;
Char std[10];
Struct stud_mark
{
Char subj_name[20];
Int subj_marks;
} marks;
} result;

Main()
{
Printf(“enter roll number “);
Scanf(“%d”, &result.rno);
Printf(“enter standard “);
Scanf(“%d”, &result.std);
Printf(“enter subject name“);
Scanf(“%d”,
&result.marks.subj_name);
Printf(“enter subject name“);
Scanf(“%d”,
&result.marks.subj_marks);
printf(“%d”, result.rno);
printf(“%d”, result.std);
printf(“%d”,
result.marks.subj_name);
printf(“%d”,
result.marks.subj_marks);
}

Array of structure

Struct stud
{
Char name[20];
Int rno;
Float avg;
};
Struct student s[20];
Eg: program for array of
structure

#include<stdio.h>
#include<string.h>
Struct student
{
Int id;
Char name[20];
Float percentage;
}
Struct student record[3];
Int main()
{
Int I;
Record[0].id=11;
Strcpy(record[0].name,”soham”
);
Record.perecentage=72.5;

Record[1].id=12;
Strcpy(record[1].name,”rohit”);
Record.perecentage=90.5;

Record[2].id=13;
Strcpy(record[2].name,”tushar”
);
Record.perecentage=80.5;
For(i=0;i<3;i++)
{
Printf(“%d” , record[i].id);
Printf(“%s”,record[i].name);

Printf(“%f”,record[i].percentage
);
}
Return 0;
}

Structure and function

1) Passing each individual


member as a separate
argument
/* program for passing each
member of a structure variable
as separate argument */
Struct student
{
Char name[20];
Int roll_no;
Int marks;
}
//Struct student
stud={ “sohan”,1,78};

Int main()
{
Void print_struct(char
name,int roll_no,int marks);
Struct student
stud={ “sohan”,1,78};
Print_struct(stud.name,stud.roll
_no,stud.marks);
Return 0;
}

Void print_struct(char
name[],int roll_no,int marks)
{
Printf(“%s”,name);
Printf(“%d”,roll_no);
Printf(“%d”,marks);
}
________________________________
___
2) Call by value

Datatype
function_name(struct_typetag_
name
{
Return(expression0;
}
/*
#include<stdio.h>
#include<string.h>
Struct student
{
Int id;
Char name[20];
Float percentage;
}
Struct student s1;

Int main()
{
Void display(Struct student
rec);
S1.id=1;
Strcpy(S1.name,”rohit”);
S1.percentage=86.1;
Display(s1);
}

Void display(Struct student


rec)
{
Printf(“%d”,rec.id);
Printf(“%s”,rec.name);
Printf(“%f”,rec.percentage);
}

Call by reference

Struct employee
{
Char name[20];
Int age ;
Char doj;
Char designation[20];
}
Struct employee
rec={ “tushar”,22,”25/02/2025
”,”developer”};
Int main()
{
Void print_struct( strucr
employee *ptr)
Print_struct(&rec);
Return;
}

Void print_struct( strucr


employee *ptr)
{
Printf(“%s”,ptrname);
Printf(“%d”,ptrage);
Printf(“%s”,ptrdoj);
Printf(“%s”,ptrdesignation);
}

Pointer and structure

Struct tag_name
{
Datatype member1;
Datatype member2;
……
}
Struct tag_name var ;
Struct tag_name *ptr;
Ptr=*var

Struct student
{
Int rno;
Char name[20];
};
Struct student s1;
Struct student *ptr;
Ptr=&s1;

Member access
Ptrrno;
Ptrname;

Or
(*ptr).rno;
(*ptr). Name;
________________________________
__
Union
A union is a special data
type available in c
It allow to store different
datatype in the same
memory location
Sysntax:
Union tag
{
Datatype member1;
…..
Datatype member n;
}var1;
Or

Union tag
{
Datatype member1;
…..
Datatype member n;
}var1,var2…..varn;
Or
Union tag
{
Datatype member1;
…..
Datatype member n;
}
Union tag va1 ;

Eg:
Union code
{
Char colour[20];
Int size;
} purse,belt;
Initialization
Union car
{
Char name[20];
Int price;
} car1={“BMW”};
Union variables
{
Char x;
Int y;
Float z;
}
Union variables
var1={‘m’,’4’,’2.5’};
Int main()
{
Printf(“%c %d
%f”,var1.x,var1.y,var1.z);
Return 0;
}

Accessing union member


Suntax:
union_name.member
Pointer
Union_pointer member

Car1.price

(*car3).price or car3  price


Difference between union
and structure

Definition structure
union
Definition It Is A union is
collectio acollectio
n of n of
logically logically
related related
element elements
s possibly
possibly of
of different
different types
types having
having a single
single name,sha
name re single
memory
location
Access We can Only one
members access member
all the of union
member cab be
of access at
structure anytime
at
anytime
Memory Memory Allocats
location is memory
located for
for all variables
member or
s or member
variables having
largest
size
Initializati All Only first
on member member
of the of a union
structure can be
can be initialized
initialize
d
Size Size of Size of
structure union
variable variable
is is equal
greater to sizes of
or equal largest
to sum member
of sizes
of its
member
Keywords Struct Union
Example Struct Union
item item
{ {
Int Int rno;
rno; Char
Char name[20]
name[20 ;
]; }
} var1 ; Vra1;

File Handling

Streams is logical interface to a


file
File is name collection of data.
File represent a sequence of
bytes text file or binary file.

File handling is used for storing


a data permanently in
computer

File handle the data in two way


Stream oriented data(text)
System oriented data(binary )

Introduction of streams

Streams is collection/sequence
of bytes.
Name of flow of data
A stream access by stream
pointe

Stream pointer
end pointer

A file is opened as stream with


the help of pointer of type file .

Two types of formats stream


1) Text stream
2) Binary stream
Files
Collection of related data .
File is sequence of streams of
bytes with end-of-file (eof).
________________________________
___
Needs of files
Real having large a,ount of data
in such we need to use file.
Program terminated or lost
Operation in files
1) Naming a file
2) Opening a file
3) Reading a file
4) Writing a file
5) Closed a file

Three steps for file


operation
1) Opening file
2) Reading or writing a
file
3) Closing a file
Function of file handling

1) fopen()
2) fclose()
3) fcloseall()
4) fgetc()

FILE *fp
Types of files (Text file and
Binary file)
Text file  Binary file -
text file
Diiference between text file and
binary file
Text file textual information
stored
Binary information in 0 an 1
formate
Text file sequence of char
organized into lines
Binary file sequence of bytes
Process the data sequentially
Process the date sequentially
and according need of
application
Text file .txt
Binary file .exe,.db
Operation on text file and
binary file
1) opening file
file has to be opened before
beginning of read and write
operation

syntax
FILE *fopen(const char
*filename,const char *mode)

Mode:
“w”: write
“r”: read
“a” : append (writing at the end
)
“w+”:reading and writing
+a
Wb
Rb
Ab
Wb+
rb+
ab+
“+r”: both writing and reading

__________________________

Program for file opening


#include <stdio.h>
#incliude <stdlib.h>
Int main()
{
File *fp;
Fp=fopen(“result.doc”,”w”)
;
If(pf==null)
{
Printf(“ I couldn’t open
result.doc”);
Exit(0);
}
Printf(“ I have open
result.doc “);
Return 0;
}

________________________________
___
2. Closing a File
To close a file use fclose()
function
Syntax:
Int fclose(file *fp);

/* Program for closing a file */


#include<stdio.h>
#include<stdlib.h>
Int main()
{
File *fp;
Int I;
Fp=fopen(“result.doc”,”w”);
If(fp== null)
{
Printf(“I couldn’t open file”);
Exit(0);
}
For(i=1;i<=10;I++)
Fprintf(fp,”%d ,%d” I,i*i);
Fclose(fp);
Return 0;
}
End of file (EOF)
feof()
/*program on feof()
Int main()
{
File *stream;
Char c ;

Stream=fopen(“sample.txt”,”r”
);
While (!feof(stream))
{
C=fgetc(stream);
Putch(c );
Text file operation
1) Writing a file
Fputs()
Int main()
{
File *fp;

Pf=fopen(“test.ext”,”w+”)
;
Fprintf( fp,this is the
testing “);
Fputs(“this is the
testing”,fp);
Printf(“check test.ext”);
Fclose(fp);
}
Reading file
Fgets()
Int main()
{
File *fp;
Char buff[20];
Fp=fopen(“text.txt”,”r”);
Fscanf(fp,”%s”,buff);
Printf(“%s”,buff);
Fgets(buff,255,
(file*)fp);
Fclose(fp);
}
______________________________
___
Binary file operation
Fwrite() write records to the
file.
It may be array or structure
______________________________
Struct student
{
Int rollno;
Char name[20];
Float marks;
}
Struct student stud;
Int main()
{
File *fp;
Char ch;
Fp=fopen(“student.dat”,”W”);
If(fp==null)
{
Printf(“cant open file “);
Exit(0);
}
Do
{
Printf(“enter rollno”);
Scanf(“%d”,&stud.rollno);
Printf(“tnter the name”);
Scanf(“%s”,stud.name);
Prinft(“enter marks”);
Scanf(“%f”,&stud.marks);

Fwrite(&stud,sizeof(stud),
1,fp);
Printf(“do you want to
add data(y/n)”);
Ch=getch();
} while(ch==’y’|| ch==’Y’);
Fclose(fp);
}

________________________________
__
Fread():
Read records from the file
Fread(ptr,int size,file *fp);

Struct student
{
Int rollno;
Char name[20];
Float marks;
}
Struct student stud;
Int main()
{
File *fp;
Char ch;
Fp=fopen(“student.dat”,”W”);
If(fp==null)
{
Printf(“cant open file “);
Exit(0);
}
While
(fread(&stud,sizeof(stud),
1,fp)>0)
Printf(“%d %s
%f”,stud.rollno,stud.name.stu
d.marks);
Fclose(fp);
}
Putw(): to write integers to the
file
Getw():to read interger value
from file
Mixed Data oriented
function

1) fprintf():It is uses to
write mixed type in the
file .

syntax:
fprintf(File *fp,”formate
string”,var_list)

/* program for fprintf() function


#include<stdio.h>
Void main()
{
File *fp;
Int rollno;
Char name[20];
Float marks;
Char ch;
Fp=fopen(“file.txt”,”w”);
If(fp==null)
{
Printf(“cant open file “);
Exit(0);
}
Do
{
Printf(“enter rollno”);
Scanf(“%d”&rollno);
Printf(“enter name “);
Scanf(“%s”,name);
Printf(“enter marks”);
Scanf(“%f”,&marks);
fprintf(fp,”%d%s
%f”,rollno,name,marks);
Printf(“do you want to add
another data(Y/N)”);
Ch=getch();
} while (ch==’Y’ || ch=’y’);
Printf(“Data written succefully”);
Fclose(fp);
}

Fscanf():
It is used to read mixed type form
file .

Syntax:
Fscanf(file
*fp,”formate_string”,var_list)

Q1: program for fscanf() function


#include <stdio.h>
Void main()
{
File *fp;
Int rollno;
Float marks;
Char name[20];
Fp=fopen(“file.txt”,”r”);
If(fp==null)
{
Printf(“cant open”);
Exit(0);
}
Fscanf(fp,””%d%s
%f”,&rollno,&name,&marks);
Printf(“%d%s
%f”,rollno,name,marks);
Fclose(fp);
}
Standard library input/output
function
<Stdio.h>
Predefine types and values
(EOF,NULL,SIZE_t)
Eof: rohit\0
Null:0
Bufsiz: i/o buffer size
Size_t:it hold any size return
sizeof()
Preopened file
streams(stdin,stdout,stderr)
File *Stdin: input stream
File *stdout: output stream
File *stderr :output stream used for
error msg
Flush file buffer(fflush())
If stream =null pointer
Fflush() open outstream
i.e
if operation (succeeds)
fflush return 0;
otherwise
EOF is return and errorno set
Read character from file
( getc(),fgetc(),getchar())
1.getc(file *stream): used to get the
character from stream.
2. fgetc(); read the next character
from the input stream
3.getchar(void):read character from
stdin

Write character to file


(putc(),fputc(),putchar())
1) Int fputc(int c,file
*stream):write to output
stream
2) Int putc(int c file *stream): put
character to stream.
3) Putchar() write character to
stdout()
_________________________________________
_
/*program for getchar() and
putchar()
#include<stdio.h>
Int main()
{
Int c;
Printf(“enter a value”);
C=getchar();
Printf(“you entered “);
Putchar(c );
Return 0;
}
Ramdom Access to file
1) In random access mode records
can be accessed in any order.
2) Records in a random access file
are numbered sequentially
beginning with number 0
3) All records in a random access
file must be of same size
Three function RAF
1) Fseek(): it is used to move the
pointer to the desired position
in the file.

Syntax :

Int fseek(File *fp,long offset,int


pos);

Offset
SEEK_SET 0
beginning of file
SEEK_CUR 1 current
position in file
SEEK_END 2 the end of
the file

/* fseek()
#
Sruct student
{
Int rollno;
Char name[20[;
Float marks;
} struct student stu;

Void mai()
{
File *fp;
Char ch;
Int offset;
Fp= fopen(“student.dat”,”r”);
If(fp==null)
{
Printf(“cant open file”);
Exit(0);
}
Offset =sizeof(stu)*-1;
Fseek(fp,offset,SEEK_END);
Fread(&stu,sizeof(stu),1,fp);
Printf(“%d” stud.rollno);
Printf(“%s”,stu.name);
Perintf(“%f”,stu.marks);
Fseek(fp,0,SEET_SET);
Fread(&stu,sizeof(stud),1,fp);
Printf(“%d” stud.rollno);
Printf(“%s”,stu.name);
Perintf(“%f”,stu.marks);
Fseek(fp,0,SEET_CUR);
Fread(&stu,sizeof(stud),1,fp);
Printf(“%d” stud.rollno);
Printf(“%s”,stu.name);
Perintf(“%f”,stu.marks);
Fclose(fp);
}

ftell(): it return the current position


of cursor on the file.

Syntax :
Long ftell(File *fp);
_________________________________________
_
/* ftell()
#
Void main()
{
File *fp;
Char ch;
Long pos;
Fp=fopen(“file.txt”,”r”);
If(fp==null)
{
Printf( “cant open file”);

While ((ch=fgetc(fp)!=EOF)
{
If (ch==’a’|| ch==’e’|| ch==’I’||
ch==’o’||ch=’u’)
{
Pos=ftell(fp);
Printf(“position of %c is at
%ld”,ch,pos);
}
}
Fclose(fp);
}

Fflush(): this function flushes the


output buffer of a stream
/* fflush()
#
Int main()
{
Char ch1 ,ch2;
Printf(“enter first character”);
Scanf(“%c”,&ch1)
Fflush(stdin);
Return 0;
}
2) fscanf()
{

You might also like