c Programming and Data Structures - Unit II Notes
c Programming and Data Structures - Unit II Notes
Structure
Definition:
Structure is a user-defined data type
It is used to store the collection of different data types elements.
Each element of a structure is called a member.
The struct keyword is used to define the structure.
Structure declaration
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example :
struct student
{
int id;
char name[10];
};
Here, struct is the keyword;
student is the name of the structure;
id and name are the members of the structure
Example:
struct student
{
int id;
char name[50];
}s1,s2;
Accessing members of the structure
1. By . (dot operator)
2. By -> (structure pointer operator)
The structure members ise accessed with structure variable with dot operator.
Syntax
Structure-variable.structure-member
#include<stdio.h>
#include <string.h>
struct student
{
int id;
char name[10];
}s1;
int main( )
{
s1.id=101;
s1.name= "Reema”;
printf( "employee 1 id : %d\n", s1.id);
printf( "employee 1 name : %s\n", s1.name);
return 0;
}
The structure members can be accessed with structure pointer variable with ->operator.
Syntax
Structure-variable->structure-member.
Nested Structure:
Declaring one structure within another structure is called as Nested structure.
Example:
struct address
{
char city[20];
int pin;
char phone[14];
};
struct student
{
char name[20];
struct address add;
};
The nested structure members are accessed with following statement
struct student s1;
s1.name=”reema”;
s1.add.city=”Madurai”;
Arrays of Structure
The collection of multiple structures variables.
Each variable contains information about different entities.
Example:
struct student
{
int id;
char name[50];
};
struct student s1[10];
Structures and Functions
Structures can be passed as function arguments like all other data types.
We can pass the C structures to functions in 3 ways:
1. Passing individual members of a structure to a function
2. Passing an entire structure to a function.
3. Passing a pointer to structure to a function.
The function can return a structure or a structure member or a pointer to a structure
Example: 1. Passing individual members of a structure to a function
#include<stdio.h>
struct student
{
int id;
char name[20];
}
void display(int a,char n[]);
int main()
{
struct student s1;
clrscr();
printf(“Enter Id”);
scanf(“%d”,&s1.id);
printf(“Enter Name”);
scanf(“%s”,s1.name);
display(s1.id,s1.name);
getch();
return 0;
}
void display(int a,char n[])
{
printf(" Id is: %d \n",a);
printf(" Name is: %s \n", n);
}
2. Passing an entire structure to a function.
#include<stdio.h>
struct student
{
int id;
char name[20];
}
void display(struct student stud );
int main()
{
struct student s1;
clrscr();
printf(“Enter Id”);
scanf(“%d”,&s1.id);
printf(“Enter Name”);
scanf(“%s”,s1.name);
display(s1);
getch();
return 0;
}
void display(struct student stud )
{
printf(" Id is: %d \n",stud. id);
printf(" Name is: %s \n",stud. name);
}
Self Referential Structure
The self-referential structure is a structure that points to the same type of
structure.
It contains one or more pointers that point to the same structure.
Self-referential structure is used in the linked list, trees, graphs and other data
structures.
Example:
struct node
{
int d1 ;
int d2 ;
struct node * link ;
};
typedef in C
Union
Definition
union is a user defined data type.
It is a collection of different variables of different data types
In union, all members share the same memory location.
Size of a union is the size of largest member in union.
The union keyword is used to define the structure.
Declaring a Union
The union keyword is used to define the structure.
Syntax:
union structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example :
union student
{
int id;
char name[10];
};
Here union is the keyword.
student is the name of the union.
id and name are the members of the union.
Int i
Char name[10]
Accessing a Member of a Union
1. By . (dot operator)
2. By -> (union pointer operator)
The union members can be accessed with union variable with dot operator.
Syntax
union-variable.union-member
#include<stdio.h>
#include <string.h>
union student
{
int id;
char name[10];
}s1;
int main( )
{
s1.id=101;
s1.name= "Reema”;
printf( "employee 1 id : %d\n", s1.id);
printf( "employee 1 name : %s\n", s1.name);
return 0;
}
The union members can be accessed with union pointer variable with ->operator.
Syntax
union-variable->union-member
Initializing Unions
The union members are initialized using the syntax
Union-variable.union-member=value;
Example
union student
{
int id;
char name[10];
}s1;
int main( )
{
s1.id=101;
s1.name= "Reema”;
printf(“%d”,s1.id);
printf(“%s”,s1.name);
return 0;
}
Arrays of Union Variables
It is the collection of multiple union variables.
Each variable contains information about different entities.
Example:
union student
{
int id;
char name[50];
};
Union student s1[10];
Here s1[10] is the array of union.
Unions Inside Structures
A union can be nested inside a structure and it is called union of structures
union ex
{
int a;
float b;
};
struct mx
{
union ex s;
};
struct ex
{
int a;
float b;
};
union mx
{
struct ex s;
};
Difference between Structure and union
Structure Union
The struct keyword is used to define a The union keyword is used to define a
structure. union.
Every member is assigned a unique memory All the data members share a same
location. memory location.
Change in the value of one data member Change in the value of one data
does not affect other data members in the member affects the value of other data
structure. members.
Initialize multiple members at a time. Initialize only the first member at once.
A structure’s total size is the sum of the size A union’s total size is the size of the
of every data member. largest data member.
Users can access or retrieve any member at Users can access only one member at a
a time. time.
Enumerated Data Type
Enumeration (or enum) is a user defined data type in C.
It is used to assign names to integral constants.
The keyword ‘enum’ is used to declare new enumeration types.
Syntax :
enum flag{constant1, constant2, constant3, ....... };
The default value of constant1 is 1 , constant2 is 2 and so on.
Example:
enum week{Mon, Tue, Wed};
enum week day;
day=mon;
The value of day is position of Mon in enum week . So the value of day is 0.
If there is no value to the enum names, then the compiler will assign the default
values starting from 0.
The enum names available can have the same value.
o enum week{Mon=0, Tue=1, Wed=1};
The values to the enum name in any order.
The unassigned names will get the default value as the previous one plus one.
The values assigned to the enum names must be integral constant, i.e., it should
not be of other types such string, float, etc.
Example:
#include <stdio.h>
int main()
{
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
enum weekdays w;
w=Monday;
printf("The value of w is %d",w);
return 0;
}
Output :
The value of w is 2
Pointers
The pointer is a variable used to store the address of another variable.
This variable can be of type int, char, array, function, or any other pointer.
The size of the pointer depends on the architecture.
In 32-bit architecture the size of a pointer is 2 byte.
Declaring a pointer
Syntax :
Datatype *pointer-variable;
Example:
Int *p1;
Initialize a pointer
After declaring a pointer, initialize the pointer with a variable address.
Syntax
pointer-variable=@variable;
Operators in pointer
Example:
int a,*p1;
a=10;
p1=&a;
a fff4 p1 fa21
10 fff4
Pointer arithmetic:
Increment/Decrement of a Pointer
The pointer can be incremented or decremented with 1..
Syntax:
new_address= current_address + size_of(data type)
new_address= current_address - size_of(data type)
Example
int a,*p1;
p1=&a;
Syntax
new_address= current_address + i * size_of(data type)
new_address= current_address - i * size_of(data type)
Example:
ptr=1002
ptr=ptr+2 will be calculated as
1002+2*sizeof(int)
1002+2*2
1002+4
1006
Example
int *ptr1,*ptr2;
ptr1=1000
ptr2=1016
Types of pointer
Null pointer
pointer created by assigning a null value to the pointer.
A Null Pointer is a pointer that does not point to any memory location.
It stores the base address of the segment.
int *p=NULL;
Example :
void *p1;
int a;
p1=@a;
*(int *)p1;
Wild pointer - If a pointer isn't initialized to anything, it's called a wild pointer.
Dangling Pointer - A dangling pointer is a pointer that refers to a memory location
that has been released or deleted.
Pointer to pointer
Pointer stores the address of another pointer is known as pointer to pointer.
The first pointer is used to store the address of a variable .
The second pointer is used to store the address of the first pointer.
Arrays of pointer
Arrays of pointer is used to store the address of multiple values of same data type.
Example
int a[10],*p[10];
p[0]=&a[0];
p[1]=&a[1];
p{2}=&a[2];
Function pointer
Function pointer points to code, not data.
we do not allocate de-allocate memory using function pointers.
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
void (*fun_ptr)(int) = &fun;
(*fun_ptr)(10);
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
int c=10,d=20;
swap(&c,&d);
getch();
return 0;
int t;
t=*a;
*a=*b;
*b=t;
function-name(arrayname);
Example :
display(a)
Syntax to declare the function that receives an array:
1. return_type function(type arrayname[])
2.return_type function(type arrayname[SIZE])
3.return_type function(type *arrayname)
Example
Void display(int a[10]);
void display(int a[]);
void display(*a);
1.malloc() function
ptr=(cast-type*)malloc(byte-size)
Example:
ptr=(int*)mallco(sizeof(int));
2.calloc() function
ptr=(cast-type*)calloc(number, byte-size)
Example:
ptr=(int*)callco(sizeof(int));
3.realloc() function
Syntax:
ptr=realloc(ptr, new-size)
4.free() function
Syntax;
free(ptr)
Example:
free(ptr1);
File Handling
File is a collection of similar records of an entity.
Record is a collection of fields.
Types of file
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files.
The text files are created using text editors such as Notepad.
2. Binary files
o There are many functions in the C library to open, read, write, search and close
the file.
No 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
Creation of a file
file-pointer = fopen(“filename”,”file-mode”);
filename is the name of the file to be opened and mode specifies the purpose of
opening the file.
3.fgetc(file-pointer);
4.fgetw(file-pointer);
Writing in to a file
The file write operations can be performed by the functions fprintf , fputs and fputc()
Syntax:
1.fprintf(filepointer,”format specifier,variables);
2.fputs(“string”,file-pointer);
3.fputc(‘single character’,file-pointer);
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.
Closing a file
The file should be closed after reading/writing.
Closing a file is with the fclose() function.
Syntax:
fclose(fptr);
fseek() function
The fseek() function is used to set the file pointer to the specified offset.
Syntax:
rewind() function
The rewind() function sets the file pointer at the beginning of the file.
Syntax:
rewind(file-pointer)
Example program:
#include<stdio.h>
#include<conio.h>
int main()
{
file *fp1,fp2;
int n,a[10],b,i;
fp1=fopen(“file1.txt”,”w”);
printf(“enter number of elements”);
scanf(“%d”,&n);
printf(“enter the array elements”);
for(i=1;i<=n;i++)
{
scanf(“%d”,&a[i]);
fprintf(fp1,”\n%d”,a[i]);
}
fclose(fp1);
fp2=fopen(“file1.txt”,”r”);
printf(“the content of the file is \n”);
while(!feof(fp1))
{
fscanf(fp2,”%d”,b);
printf(“%d”,b);
}
fclose(fp2);
getch();
return 0;
}
Strings
String is an array of characters.
NULL character (\0) will automatically be inserted at the end of the string.
String Declaration
Syntax:
char stringname[size];
Example
char name[10];
Reading and writing a string
gets() – This function is used to read a string
puts – This function is used to display the string
%s – format specifier is used to read a string with scanf() function
Example :
char name[10];
scanf(“%s”,name);
gets(name);
puts(name);
String functions:
No Function Description
.
1) strlen(string_name) returns the length of string name.
2) strcpy(destination, copies the contents of source string to
source) destination string.
3) strcat(first_string, joins first string with second string. The
second_string) result of the string is stored in first string.
4) strcmp(first_string, compares the first string with second string.
second_string) If both strings are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
Example
char firstname[]=”reema”
char lastname[]=”thareja”
1.strlen(firstname)- output is 5
2.strcpy(name,”data structures”)- the value of name is data structures
3.strcat(firstname,lastname)- now the value of fistname is reema thareja
4.strcmp(firstname,lastname)- the output is not zero because the two string are
different.
5.strrev(lastname)- the output is ajerath
6.strupr(lastname) – the output is THAREJA.
Preprocessor directives
The C preprocessor is a micro processor used by compiler to transform the c program
before compilation.
Preprocessor directives.
1. Macros
1. Object Macros
2. Function Macros
Object macro:
Example:
#define pi 3014
Function Macros
Example :
#define area(I,b)(l*b)
2. File Inclusion
This type of preprocessor directive used to include a file in the source code program.
1.Standard files
These files contain definitions of pre-defined functions like printf(), scanf(), etc.
Syntax:
#include< file_name >
Example:
#include<stdio.h>
The user defined files are included with the syntax #include “filename”
Example:
#include “program1.c”
3.Conditional Compilation
These directives are used to compile a specific portion of the program or to skip the
compilation of some specific part of the program based on some conditions.
This can be done with the help of the two preprocessing commands ‘ifdef‘ and
‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
4. Other Directives
#pragma startup and #pragma exit: Used to run a function before program
startup and. before program exit
o #pragma warn -rvl: This directive hides those warnings raised when a
function does not return a value.
o #pragma warn -par: This directive hides warnings raised when a
function does not use the parameters passed to it.
Preprocessor Operators