FCS_Module-5_Notes[Structure & Uinx]
FCS_Module-5_Notes[Structure & Uinx]
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.
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()
{
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:");
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);
}
#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)
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:-
An array whose elements are of type structure is called array of structure.
It is generally useful when we need multiple structure variables in the program.
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);
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;
};
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. We can
also pass structures using call by value and call by reference methods. A function in C may also return
a struct data type.
Passing structures to functions can be done in the following ways
– Passing individual members
– Passing entire structure or structure variable.
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()
{
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);
}
Pointer of Structures:
A structure pointer is defined as the pointer which points to the address of the memory block that
stores a structure known as the structure pointer.
Accessing the Structure Member with the Help of Pointers
There are two ways to access the members of the structure with the help of a structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot operator.
2. With the help of ( -> ) Arrow operator.
To access the structure members using the structure pointer with the help of the dot operator.
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{
struct Student s1;
struct Student* ptr = &s1;
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;
return 0;
}
To access the structure members using the structure pointer with the help of the 1. Arrow
operator.
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
struct Student s, *ptr;
int main()
{
ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch);
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);
return 0;
}
Self-referential Structures:
It is a structure that points to the same type of structure. It contains one or more pointers that
ultimately point to the same structure.
o The self-referential structure is widely used in dynamic data structures such as trees,
linked lists, etc.
o In this type of structure, the object of the same structure points to the same data structure
and refers to the data types of the same structure.
o It can have one or more pointers pointing to the same type of structure as their member
Syntax:
struct node {
int data1;
char data2;
struct node* link;
};
#include <stdio.h>
struct mystruct{
int a;
struct mystruct *b;
};
int main(){
struct mystruct x = {10, NULL}, y = {20, NULL}, z = {30, NULL};
struct mystruct * p1, *p2, *p3;
p1 = &x;
p2 = &y;
p3 = &z;
x.b = p2;
y.b = p3;
printf("Address of x: %d a: %d Address of next: %d\n", p1, x.a, x.b);
printf("Address of y: %d a: %d Address of next: %d\n", p2, y.a, y.b);
printf("Address of z: %d a: %d Address of next: %d\n", p3, z.a, z.b);
return 0;
}
Typedef:
• The typedef keyword gives a meaningful name to the existing data type which helps other
users to understand the program more easily.
• It can be used with structures to increase code readability and we don’t have to type struct
repeatedly.
• The typedef keyword can also be used with pointers to declare multiple pointers in a single
statement.
• It can be used with arrays to declare any number of variables.
#include <stdio.h>
#include <string.h>
int main()
{
stu st;
strcpy(st.name, "Kamlesh Joshi");
strcpy(st.branch, "Computer Science And Engineering");
st.ID_no = 108;
Union:- A union is a special data type available in C that allows to store different data types
in the same memory location. we can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of using the
same memory location for multiple-purpose.
Syntax for declaring a union is same as that of declaring a structure except the keyword struct.
union union_name {
datatype field_name;
datatype field_name;
// more variables
};
#include <stdio.h>
struct store
{
double price;
union
{
struct{
char *title;
char *author;
int number_pages;
} book;
struct {
int color;
int size;
char *design;
} shirt;
}item;
};
int main()
{
struct store s;
s.item.book.title = "C programming";
s.item.book.author = "John";
s.item.book.number_pages = 189;
printf("Size is %ld", sizeof(s));
return 0;
}
Bit-fields:
In addition to declarators for members of a structure or union, a structure declarator can also be a
specified number of bits, called a " bit field.
Bit field are used to specify the size (in bits) of the structure and union members .
Need of Bit Fields in C
• Reduces memory consumption.
• To make our program more efficient and flexible.
• Easy to Implement.
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
File Handling in C:
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file handling to
perform all file operations such as read, write, close, etc. FILE macro is used to declare the file
pointer variable. The FILE macro is defined inside <stdio.h> header file.
Syntax of File Pointer
FILE* pointer_name;
The fopen() function is used to open a file. The syntax of the fopen() is given below.
1. FILE *fopen( const char * filename, const char * mode );
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
2. The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:
int fclose( FILE *fp );
Example: Program to Create a File, Write in it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
FILE* filePointer;
char dataToBeWritten[50] = " A Computer " Science Portal ";
if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {
printf("The file is now opened.\n");
if (strlen(dataToBeWritten) > 0) {
fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}
fclose(filePointer);
printf("Data successfully written in file " "GfgTest.c\n");
printf("The file is now closed.");
}
return 0;
}
fseek():
To access a particular record inside a file that is at a specific position, so we need to loop
through all the records before it to get the record. Doing this will waste a lot of memory
and operational time. To reduce memory consumption and operational time we can
use fseek() .
It provides an easier way to get to the required data. fseek() function in C seeks the cursor
to the given record in the file.
Syntax for fseek()
int fseek(FILE *ptr, long int offset, int pos);
// C Program to demonstrate the use of fseek() in C
#include <stdio.h>
int main()
{
FILE* fp;
fp = fopen("test.txt", "r");
rewind():
The rewind() function is used to bring the file pointer to the beginning of the file.
It can be used in place of fseek() when we want the file pointer at the start.
Syntax of rewind():
rewind (file_pointer);
return 0;
}
Preprocessor Directives
Preprocessor Directives:-Preprocessor is a program which is invoked by the compiler before
the compilation of the user written program
–The declaration of preprocessor statements always begin with # symbol
–These statements are usually placed before the main( ) function.
Types of Preprocessors:-
–Macros
–File Inclusion
–Conditional compilation
–Other directives
Macros:-These are the piece of code in the program which is given some name.
• Whenever the name is encountered by the compiler in the program , the compiler replaces the
name with the actual piece of code.
• The “#define” directive is used to define a macro.
/*C Program that finds the addition of two squared numbers, by defining macro for
Square(x).*/
#include <stdio.h>
#define square(x) (x*x)
void main( )
{
int n1, n2, sum;
printf(“Enter two numbers”);
scanf(“%d%d”, &n1, &n2);
sum = square(n1) + square(n2);
printf(“Sum of two squared numbers = %d”, sum);
}
File Inclusion:-This type of preprocessor directive tells the compiler to include a file in the
source code program
These files contains the definition of the predefined functions like printf( ), scanf( ), etc.
Different functions are declared in different header files.
/* C program to demonstrate file inclusion */
#include<stdio.h>
#include<math.h>
void main()
{
int num;
float res;
printf("Enter a number\n");
scanf("%d",&num);
res=sqrt(num);
printf("Squareroot of %d = %f\n",num,res);
}
Conditional Compilation: -these are the type of directives that helps to compile a specific
portion of the program or to skip a specific part of the program based on some conditions.
Some of the conditional compilation directives are
– #ifdef, #ifndef, #if, #else
Other Directives:-Apart from the above directive there are two more directives which are not
commonly used
#undef directive:-this directive is used to undefined a value which was declare using the
#define directive