Unit 2 C Programming and Data Structures-1
Unit 2 C Programming and Data Structures-1
2.1 INTRODUCTION
➢ Structures, unions and enumerations are known as user defined data types.
➢ These data types are used to create a flexible new data type.
➢ Structure can be used for the storage of different data types. The similarity
between structure and array is both contain a finite number of elements.
➢ Union is similar to structures in all aspects except the manner in which their
constituent elements are stored.
➢ In structures, separate memory is allocated to each element, while in unions all
the elements are share the same memory.
➢ Enumeration helps to define a data type whose objects can take a limited set of
values.
2.2 STRUCTURE
Definition
➢ A Structure is a collection of variables of different data types under a single
name and provides a convenient way of grouping several of related information
together.
➢ Unlike arrays, it can be used for the storage of heterogeneous data (data of
different data types).
1.
1. Defining Structure
2. Initializing structure elements
3. Declaring variables and constants (objects) of the newly created type.
2.3 UNION
➢ Union can be defined as a user-defined data type which is a collection of
different variables of different data types in the same memory location. The
union can also be defined as many members, but only one member can contain a
value at a particular point in time. Unions provide an efficient way of using the
same memory location for multiple-purpose.
➢ Union is a user-defined data type, but unlike structures, they share the same
memory location.
Defining a Union
➢ To define a union, you must use the union statement in the same way as did
while defining a structure. The union statement defines a new data type with
more than one member for your program. The format of the union statement is
as follows:
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
➢ The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end
of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str.
union Data {
int i;
float f;
char str[20];
} data;
➢ Now, a variable of Data type can store an integer, a floating-point number, or a
string of characters. It means a single variable, i.e., same memory location, can be
used to store multiple types of data. You can use any built-in or user defined data
types inside a union based on your requirement.
Example Program 2.9 Illustration of Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
void main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "Charulatha publication");
printf( "data.str : %s\n", data.str);
}
Output
data.i : 10
data.f : 220.500000
data.str : Charulatha publication
Difference between Structure and Union
Sl.No Structure Union
1 The member of a structure occupies The member of union share same
its own memory space. memory space.
2 The keyword struct is used to define The keyword union is used to define a
a structure structure
3 All the members of a structure can Only the first member of a union can
be initialized. be initialized.
4 In structure, each member is stored In union, all members are stored in
in a separate memory location. So the same memory locations. So, need
need more memory space. less memory space.
2.4 POINTERS
2.4.1 Pointers to Variables
➢ A pointer is a variable that stores an address of another variable of same type.
➢ Pointer can have any name that is legal for other variable.
➢ Pointer variables are declared with prefix of ‘*’ operator.
➢ Using a pointer variable, we can access the value of another variable assigned to
it.
Syntax
data_type *pointer_name;
Example
int *a;
➢ variable *a can store the address of any integer type variable.
➢ A pointer is a variable whose value is also an address.
➢ Each variable has two attributes
✓ Value
✓ Address
We can define pointers in two ways.
i) First a pointer is a variable and assigns different values to a pointer variable.
ii) Second the value contained by a pointer must be an address which indicates the
location of another variable in the memory. So, pointer is called as “address
variable”.
Example
int a=50;
int *ptr;
ptr=&a;
➢ Here ‘a’ is a variable holds a value 50 and stored in a memory location 1001.
‘*ptr’ is pointer variable holds a address of a variable ‘a’.
Advantages of Using Pointers
➢ Pointers are more compact and efficient code.
➢ Pointers can be used to achieve clarity and simplicity.
➢ Pointers are used to pass information between function and its reference point.
➢ A pointer provides a way to return multiple data items from a function using its
function arguments.
➢ Pointers also provide an alternate way to access an array element.
➢ A pointer enables us to access the memory directly.
Example Program 2.10
/*C program for printing value and address of a variable using pointer variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *ptr;
ptr=&i;
clrscr();
printf(“Address of i=%u\n”,ptr);
printf(“value of i=%d\n”,*ptr);
getch();
}
Output:
Address of i=65524
value of i=3
Example Program 2.11
/*C program for printing value and address of a variable using pointer variable by
various methods*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=4;
int *j;
j=&i;
clrscr();
printf(“Address of i=%u\n”,&i);
printf(“Address of i=%u\n”,j);
printf(“Address of j=%u\n”,&j);
printf(“value of j=%u\n”,j);
printf(“value of i=%d\n”,i);
printf(“value of i=%d\n”,*(&i));
printf(“value of i=%d\n”,*j);
getch();
}
Output
Address of i=65524
Address of i=65524
Address of j=65522
value of j=65524
value of i=4
value of i=4
value of i=4
Example Program 2.12
/*C program to add two numbers using pointers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*p,*q,sum;
clrscr();
printf(“Enter two integers”);
scanf(“%d %d”,&a,&b);
p=&a;
q=&b;
sum=*p+*q;
printf(“sum=%d”,sum);
getch();
}
Output
Enter two integers 2 3
sum=5
1. fopen () : It creates a new file for use or opens an existing file for use.
2. fclose (): It closes a file which has been opened for use.
3. fscanf( file pointer, format string, address of the variable)
Example: fscanf(fptr,”%d”, &num);
4. fprintf(console output, “format string”, file pointer);
Example: fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
5. getw (): This function returns the integer value from a given file and increment the
file pointer position to the next message.
Syntax: getw (fptr);
Where fptr is a file pointer which takes the integer value from file.
6. putw (): This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a given file.
Example Program for getw() and putw()
Program 2.24: Write a program to read integer data from the user and write it
into the file using putw() and read the same integer data from the file using getw()
and display it on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
clrscr();
fp=fopen(“c.dat”, “wb+”);
printf(“Enter the integer data”);
scanf(“%d”,&n);
while(n!=0)
{
putw(n,fp);
scanf(“%d”,&n);
}
rewind(fp);
printf(“Reading data from file”);
while((n=getw(fp))!=EOF)
{
printf(“%d\n”,n);
}
fclose(fp);
getch();
}
7. fwrite()
➢ This function is used for writing an entire block to a given file.
Syntax: fwrite(ptr,size,nst,fptr);
ptr is a pointer ,it points to the array of structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
8. fread()
➢ fread(ptr,size,position,fptr);similar to fwrite
Program 2.25: program for fwrite():
Write a program to read an employee details and write them into the file at a time
using fwrite().
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen(“emp.dat”, “wb”);
clrscr();
printf(“Enter employee number”);
scanf(“&d”,&e.eno);
printf(“Enter employee name”);
fflush(stdin);
scanf(“%s”,e.ename);
printf(“Enter employee salary”);
scanf(“%f”,&e.sal);
fwrite(&e,sizeof(e),1,fp);
printf(“One record stored successfully”);
getch();
}
Operations for Search data in a file
1. fseek()
2. ftell()
3. rewind()
fseek() : Getting data using fseek()
➢ When many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record. This
will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
fseek(file pointer, displacement, pointer position);
➢ he first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.
➢ This function is used for seeking the pointer position in the file at the specified
byte.
Syntax: fseek( file pointer, displacement, pointer position);
file pointer - It is the pointer which points to the file.
displacement -It is positive or negative.
➢ This is the number of bytes which are skipped backward (if negative) or forward
(if positive) from the current position. This is attached with L because this is a
long integer.
Pointer position: This sets the pointer position in the file.
Value Pointer position Value Pointer position
0 Beginning of file.
1 Current position
2 End of file
Example:
1. fseek( p,10L,0)
➢ This 0 means pointer position is on beginning of the file, from this statement
pointer position is skipped 10 bytes from the beginning of the file.
2. fseek( p,5L,1)
➢ This 1 means current position of the pointer position. From this statement
pointer position is skipped 5 bytes forward from the current position.
3. fseek(p,-5L,1):
➢ From this statement pointer position is skipped 5 bytes backward from the
current position.
User can only use the function but User can use this type of function.
cannot change (or) modify this function. User can also modify this function.