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

POP Module 4

Pop notes

Uploaded by

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

POP Module 4

Pop notes

Uploaded by

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

Principles of Programming Using C BPOPS203

Module – 5 – Structure, Union, and Enumerated Data Type

Structure : Structure is a collection of one or more variables of same or different data types
grouped to gather under a single name for easy handling.
Structure is a user defined data type that can store related information about an entity. Structure
is nothing but records about a particular entity.

Declaration of a Structure :- A structure is declared using the keyword struct followed by


structure name and variables are declared within a structure
The structure is usually declared before the main( ) function.
Syntax : -

struct structure_name

datatype member 1;

datatype member 2;

datatype member 3;

.......................

.......................

datatype member n;

};

Example :-

struct employee

int emp_no;

char name[20];

int age;
float emp_sal;

};

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Initialization of structure :- A structure initialization is done after the declaration of the


structure
Syntax :- struct structure_name structure_variable _name;

Example :-
struct employee emp1;

Accessing structure members :- A structure uses a .(dot) [Member Access Operator] to access
any member of the structure.
Example :-
emp1.emp_no =12345;

Initialization of structure variables :-

struct employee

int emp_no;

char name[20];

int age;
float emp_sal;

} emp1={65421, “Hari”,29,25000.00};

The order of values enclosed in the braces must match the order of members in the structure
definition.

/* C program to read and print the details of employee using structures –static allocation of
variables */

#include<stdio.h>

#include<string.h>

struct employee
{

int emp_no;
char empname[20];

int age;
float emp_sal;

};
void main()
Information Science and Engineering, JIT
Principles of Programming Using C BPOPS203

struct employee emp1;


emp1.emp_no = 65421;

strcpy(emp1.empname,"Hari");
emp1.age=29;
emp1.emp_sal=25000.00;
printf("Employee Number=%d\n",emp1.emp_no);

printf("Employee Name=%s\n",emp1.empname);

printf("Employee Age=%d\n",emp1.age);

printf("Employee Salary=%f\n",emp1.emp_sal);

/* C program to read and print the details of employee using structures –run time allocation of
variables */

#include<stdio.h>

#include<string.h>

struct employee
{

int emp_no;
char empname[20];

int age;
float emp_sal;

};

void main()

struct employee emp1;


printf("Enter Employee Number:");

scanf("%d",&emp1.emp_no);
printf("Enter Employee Name:");

scanf("%s",emp1.empname);
printf("Enter Employee age:");

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

scanf("%d",&emp1.age);
printf("Enter Employee salary:");

scanf("%f",&emp1.emp_sal);
printf("Employee Number=%d\n",emp1.emp_no);

printf("Employee Name=%s\n",emp1.empname);

printf("Employee Age=%d\n",emp1.age);

printf("Employee Salary=%f\n",emp1.emp_sal);

/* C Program to find Sum of Two Complex Numbers*/

#include<stdio.h>

struct complex
{

int real;

int img;

};

void main() {

struct complex a,b,c;


printf("Enter the First Complex Number\n");

printf("Enter the real part:");

scanf("%d",&a.real);
printf("Enter the imaginary part:");

scanf("%d",&a.img);
printf("Enter the Second Complex Number\n");

printf("Enter the real part:");

scanf("%d",&b.real);
printf("Enter the imaginary part:");

scanf("%d",&b.img);
c.real=a.real+b.real;
c.img=a.img+b.img;
if(c.img>=0)
Information Science and Engineering, JIT
Principles of Programming Using C BPOPS203

printf("Sum of two Complex Number = %d+i%d\n",c.real,c.img);

else

printf("Sum of two Complex Number = %d %di\n",c.real,c.img);

Array of Structures :- if we want to store the data of 100 employees we would require 100
structure variables from emp1 to emp100 which is definitely impractical the better approach
would be to use the array of structures.

/* C program to illustrate array of structures */

#include<stdio.h>

#include<string.h>

struct employee
{

int emp_no;
char empname[20];

int age;
float emp_sal;

};
void main() {

struct employee emp1[20];


int n,i;
printf("Enter the number of employee entries\n");

scanf("%d",&n);
for(i=0;i<n;i++)
{

printf("Enter the details of employee %d\n",i+1);

printf("Enter Employee Number:");

scanf("%d",&emp1[i].emp_no);
printf("Enter Employee Name:");

scanf("%s",emp1[i].empname);

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

printf("Enter Employee age:");

scanf("%d",&emp1[i].age);

printf("Enter Employee salary:");

scanf("%f",&emp1[i].emp_sal);

}
printf("\nEMP_NO\t EMP_NAME\t EMP_AGE\t\t EMP_SALARY \n");

for(i=0;i<n;i++)

printf("%d\t%s\t%d\t%f\n",emp1[i].emp_no,emp1[i].empname,emp1[i].age,emp1[i].e

mp_sal);

Nested Structures :- A nested structure is a structure that contains another structure as its
member.
Syntax :-
struct structure_name1

{
datatype member 1;

datatype member 2;

};

struct structure_name2 {

datatype member 1;

datatype member 2;
struct structure_name1 var1;

};

/* C program to demonstrate nested structures */

#include<stdio.h>

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

struct stud_dob
{

int day;

int month;

int year;

};

struct student {

int rollno;
char sname[20];

struct stud_dob date;

};

void main() {

struct student s;
printf("Enter Student Rollno :");
scanf("%d",&s.rollno);
printf("Enter Student Name :");
scanf("%s",s.sname);
printf("Enter date of birth as day month year:");
scanf("%d%d%d",&s.date.day,&s.date.month,&s.date.year);
printf("Student Details are\n");
printf("Student Rollno = %d\n",s.rollno);
printf("Student Name=%s",s.sname);
printf("Student DOB= %d-%d-%d\n", s.date.day, s.date.month, s.date.year);

Structures and Functions :- Structures can be passed to functions and returned from it.
Passing structures to functions can be done in the following ways

• – Passing individual members


• – Passing entire structure or structure variable.

Passing Individual Members :-


while invoking the function from main( ) in the place of actual arguments we can pass the
structure member as an argument.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

#include<stdio.h>
void add(int x,int y);
struct addition
{

int a;

int b; };

void main() {

struct addition sum;


printf(" Enter two numbers\n");

scanf("%d%d",&sum.a,&sum.b);

add(sum.a,sum.b);

}
void add(int x,int y) {

int res;
res=x+y;

printf("Resultant=%d\n",res);

Passing Entire structure or structure variable :-while invoking the function


instead of passing the individual members the entire structure, i.e. the structure variable is
passed as a parameter to the function.

#include<stdio.h>

struct addition
{

int a;

int b;

};

void add(struct addition sum);

void main() {

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

struct addition sum;


printf(" Enter two numbers\n");

scanf("%d%d",&sum.a,&sum.b);

add(sum);

void add(struct addition sum)

int res;
res=sum.a+sum.b;

printf("Resultant=%d\n",res);

Size of structure :
Size of structure can be found out using sizeof() operator with structure variable name or tag
name with keyword.

sizeof(struct student);

or

sizeof(s1);

sizeof(s2);

Size of structure is different in different machines. So size of whole structure may not be equal to
sum of size of its members.

Unions:
Union:-

A union is a special data type available in C that allows to store different data
in the same memory location. You can define a union with many members, but onlyone member
can contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Syntax for declaring a union is same as that of declaring a structure except the keyword struct.

types

union union_name

datatype field_name;

datatype field_name;

// more variables

};

Difference betweeen Union and Structure:

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Accessing a member of a Union :


Member of union can be accessed using the same syntax as that of a structure. To
access the fields of a union, use the dot operator (.), i.e., the union variable name followed by the
dot operator followed by member name.

Initializing Unions:
A striking difference between a structure and a union is that in case of a Union, the fields share
the memory space, so fresh data replaces any existing data.
Look at the following code and observe the difference between a structure and union when their
fields are tobe initialized.
#include<stdio.h>
typedef struct POINT 1
{
int x, y;
};
typedef union POINT2
{
int x;
int y;
};
int main( )
{
POINT1 P1 = {2,3}
// POINT P2 = {4,5}; illegal with union
POINT2 P2;
P2.x = 4;
P2.y = 5;
Printf(“the co-ordinates of P1 are %d and %d , P1.x, P1.y“);
Printf(“the co-ordinates of P2 are %d and %d , P2.x, P2.y“);

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

}
******Output*******
The co-ordinates of P1 are 2 and 3
The co-ordinates of P2 are 5 and 5

Array of Union Variables:


Like structure we can also have an array of union variables.
However, because oft he problem of new data overwriting existing data in the other fields, the
program may not display the accurate results.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Enumeration Datatype :
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.
enum state{Working = 1, Failed = 0};
enum declaration
enum flag{constant1, constant2, constant3, ........ };
//The name of enumeration is "flag" and the constantare the values of the flag.
//By default, the valuesof the constants are as follows:
// constant1 = 0, constant2 = 1, constant3 = 2 and so on.

Variables of type enum can be defined in two ways:


enum week{Mon, Tue, Wed};
enum week day;
// Or
enum week{Mon, Tue, Wed}day;
In both of the below cases, "day" is defined as the variable of type week.
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output : 2

*/ For more Refer text book for enumarated datatypes /*

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Files :
File is a collection of data stored on a secondary storage devices like hard disks.
The file is a permanent storage medium in which we can store the data permanently.
FILE is type defined structure and it is defined in a header file “stdio.h”. FILE is a
derived data type.FILE is not a basic data type in C language.
Input File: An input file contains the same items that might have typed in from
the keyboard.
Output File: An output file contains the same information that might have been
sent to the screen as the output from the program.
Text(data) File:A text file is the one where data is stored as a stream of characters
that can be processed sequentially.

Types of files:
1. ASCII text File
2. Binary File
• ASCII Text Files :
A text file is a stream of characters that can be sequentially processed
by a computer in forward direction. For this reason, a text file is usually opened for only
one knid of operation (reading, writing, or appending) at any given time. Because text files
only process characters, they can only read or write data one character at a time. In C, a
text stream is treated as a special kind of file.

In a text file, each line contains zero or more characters and ends with one or more
characters that specify the end of line. Each line in a text file can have a maximum of 255
characters. A line in a text file is not a C string, so it is not terminated by a null character.

In a text file, each line of data ends with a newline character. Each file ends with a special
character called the end-of-file (EOF) marker.

• Binary Files:
A binary file may contain any type of data, encoded in binary form for
computer storage and processing purposes. Like a text file, a binary file is a collection of
bytes. In C, a byte and a character are equivalent. Therfore, a binary file is also referred to
as a character stream with the following two essential differences:
Information Science and Engineering, JIT
Principles of Programming Using C BPOPS203

1) binary file does not require any special processing of the data and each byte of data is
transferred to or from the disk unprocessed.
2) C places no restrictions on the file, and it may be read from, or written to, in any
manner the programmer wants.
While text files can be processed sequentially. binary files, no the other hand, can be either
processed sequentially or randomly depending on the needs of the application. In C, to
process a file randomly, the programmer must move the curent file position to an
appropriate place in the file before reading or writing data.

Steps to be perform file manipulations :


1. Declare a file pointer variable
2. Open a file
3. Read the data from the file or write the data into file
4. Close the file
• Declare a file pointer variable
 Like all the variables are declared before they are used, a file pointer variable
should be declared.
 File pointer is a variable which contains starting address of file.

 It can be declared using following syntax: FILE *fp;


Example:
#include <stdio.h>
void main()
{

FILE *fp; /* Here, fp is a pointer to a structure FILE */


---------------------------
-------------------------
}

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

2. File open Function


The file should be opened before reading a file or before writing into a file.
Syntax:
FILE *fp;
…………
fp = fopen(filename, mode)
Where,
fp is a file pointer
fopen() function to open file
mode is "r" , "w","a"
◦ fopen() function will return the starting address of opened file and it is stored file pointer.
◦ If file is not opened then fopen function returns NULL
if (fp == NULL)
{
printf(Error in opening the filen");
exit(0);
}
Modes of File:
The various mode in which a file can be opened/created are:

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

1. Read Mode("r")
◦ This mode is used for opening an existing file to perform read operation.
◦ The various features of this mode are
◦ Used only for text file
◦ If the file does not exist, an error is returned
◦ The contents of the file are not lost
◦ The file pointer points to beginning of the file.

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT


Principles of Programming Using C BPOPS203

Information Science and Engineering, JIT

You might also like