IP Unit 5
IP Unit 5
Note: The members of the structure may be any of the common data type,pointers, arrays or even the
other structures. Structure definition starts with the open brace({) and ends with closing brace(})
followed by a semicolon (;).
In the structure declaration, the structure variable can be declared after the closing brace (}).
Following example shows this.
struct date
{
int day;
int month;
int year;
}dob, doj;
Here date is the structure tag, while dob and doj are variables type date.
Using the structure tag: The variables of structure may also be declared separately by using the
structure tag as shown below:
struct date
NS Raju Institute of Technology Page 1
Introduction to Programming (AR23) Unit-V
{
int day;
int month;
int year;
}dob, doj;
Nested Structure in C : One structure with in another structure is called Nested Structure.
For example, we may need to store the address of an entity employee in a structure. The attribute address
may also have the subparts as street number, city, state, and pin code. Hence, to store the address of the
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information ...\n");
printf("name:%s\nCity:%s\nPincode:%d\nPhone:%s",emp.name,emp.add.city,emp.add.pi
n, emp.add.phone);
}
OUTPUT: Enter employee information? saivijayawada
123123
1234567890
Printing the employee information....
name: sai
City: Vijayawada
Pincode: 123123
Phone: 1234567890
Array of structures : An array of structures in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The array of structures in C
are used to store information about multiple entities of different data types. The arrayof structures is also
known as the collection of structures.
EXAMPLE
#include<stdio.h>
#include<string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{
int i;
Union: A Union is a user defined data type like structure. The union groups logically related
variables into a single unit. In structure each member has its own memory location; whereas
the members of union has the same memory location. We can assign values to Only one member
at a time can be assigned with values.
When a union is declared, compiler allocates memory locations to hold largest data type member in
the union. So, union is used to save memory. Union is useful when it is not necessary to assign the
values to all the members of the union at a time.
Union can be declared as: The union keyword is used to define the union. Let's see the syntax to
define union in c.
union union_name
{
data_type member1;
data_type member2;
data_type memberN;
};
NS Raju Institute of Technology Page 4
Introduction to Programming (AR23) Unit-V
Example:
union employee
{
int id;
char name[50];
float salary;
};
Union example program:
#include <stdio.h>
#include <string.h>
union employee
{
int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=1; strcpy(e1.name, "jai");//copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output: employee 1 id : 6906195
employee 1 name : jai
Note: According to Union id gets garbage value because name has large memory size. So only name
will have actual value.
Union example 2:
#include<stdio.h>
union student
{
char name[15];
int age;
};
int main()
{
union student st;
printf("Enter student name:");
scanf("%s",st.name);
printf("Student Name: %s & Age= %d\n",st.name,st.age);
st.age=20;
printf("Student Name: %s, age= %d\n",st.name,st.age);
}
OUTPUT: Enter student name: Jai
Student Name: jai & Age= 20
Student Name: Jai, age= 20
NOTE: First time union member name has a value which is inputted through the keyboard. So name is
displayed. Next time we were assigned a values to age, union will lost the value in member name, so
NS Raju Institute of Technology Page 5
Introduction to Programming (AR23) Unit-V
this time only student’s age is displayed.
We can access only one member of union at a time. We can’t access all member values at the same time
in union. But, structure can access all member values at the same time. This is because, Union allocates
one common storage space for all its members. Whereas Structure allocates storage space for all its
members separately.
C Typedef : The typedef is a keyword used in C programming to provide some meaningful names to
the already existing variable in the C program. It behaves similarly as we define the alias for the
commands. In short, we can say that this keyword is used to redefine the name of an already existing
variable.
Syntax of typedef:
typedef <existing_name> <alias_name>;
In the above syntax, 'existing_name' is the name of an already existing variable while 'alias name' is
another name given to the existing variable.
Example: typedef unsigned int unit;
/*In the above statements, we have declared the unit variable of type unsigned int by using a typedef
keyword.
Now, we can create the variables of type unsigned int by writing the following statement:*/ unit a, b;
//instead of writing: unsigned int a, b;
TYPEDEF EXAMPLE 1:
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10; j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
OUTPUT: Value of i is :10
Value of j is :20
TYPEDEF EXAMPLE 2:
#include <stdio.h>
int main()
{
typedef int rectangle; //creating new data type name rectangle using typedef
rectangle length, breadth, area; //declaring variables using new data type name rectangle
printf("\nEnter length and breath of the rectangle ");
scanf("%d %d ", &length, &breadth);
area = length * breadth;
printf("\nArea = %d ", area);
return 0;
}
OUTPUT: Enter length and breadth of the rectangle 5 2
Area=10
In above syntax enum is a keyword. It is a user defined data type. tagname is our own variable. tagname
is any variable name. value1, value2, value3,. Are
In above code first line is creating user defined data type called week. week variable have 7 values which
are inside { } braces.
today variable is declared as week type which can be initialize any data or value among 7 (sun, mon,).
Enum example:
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
int days;
printf("enter a day:");
scanf("%d",&days);
switch(days)
{
case sunday: printf("Today is sunday"); break;
case monday: printf("Today is monday"); break;
case tuesday: printf("Today is tuesday"); break;
case wednesday: printf("Today is wednesday"); break;
case thursday: printf("Today is thursday"); break;
case friday: printf("Today is friday"); break;
case saturday: printf("Today is saturday"); break;
FILES IN C
File : A File is a collection of related data stored on the hard disk.
Advantages of Files:
1. When large volumes of data are to be handled by the program.
2. When the data need to be stored permanently without getting destroyed when the program is
terminated.
The operations that you can perform on a File in C are −
1. Creating a new file
2. Opening an existing file
3. Reading data from an existing file
4. Writing data to a file
5. Moving data to a specific location on the file
6. Closing the file
Defining and Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to open a file.
The syntax of the fopen() is given below.
FILE *fp;
fp = fopen(“filename”, “mode”);
Example: fp = fopen(“hello.txt”, “w”);
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
a) getc() – This function is used to read characters from the file that has been opened for read operation.
Syntax : c = getc(filepointer);
This statement reads a character from the file pointed by file pointer and assigns to c.
f) fscanf() – This function works similar to scanf function. Reads a set of data from a file.
Syntax: fscanf(fp, “controlstring”, list);
here fp is the filepointer opened in write mode.
Controlstring contains output specifications for the variables in the list.
List is the name of the variables.
g) fclose() – A file can be closed as soon as all operations on it have been accepted.
Syntax: fclose(filepointer);
/* read and write the content of the file using fprintf() and fscanf() functions */
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
fptr = fopen("abc.txt", "w"); /* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %f\n", salary);
fclose(fptr);
}
2. ftell() – This function returns the current position of the file position pointer. The value is counted
from the beginning of the file.
Syntax: ftell(FILE *fp);
3. rewind() – This function is used to move the file pointer to the beginning of the file. This function is
useful when we open file for update.
Syntax: void rewind(FILE *fp);
void main()
{
FILE *fp1, *fp2;
char ch;
int pos;
clrscr();
if ((fp1 = fopen("File_1.txt","r")) == NULL)
{
printf("\nFile cannot be opened");
return;
}
NS Raju Institute of Technology Page 12
Introduction to Programming (AR23) Unit-V
else
{
printf("\nFile opened for copy...\n ");
}
fp2 = fopen("File_2.txt", "w");
fseek(fp1, 0L, SEEK_END); // file pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET); // file pointer set at start
while (pos--)
{
ch = fgetc(fp1); // copying file character by character
fputc(ch, fp2);
}
getch();
fcloseall();
}