unit4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

PART A

1.What is a nested structure?


When a structure contains another structure, it is called nested structure. For example,we have
two structures named Address and Employee. To make Address nested to Employee, we have to
define Address structure before and outside Employee structure and create an object of Address
structure inside Employee structure.
Syntax for structure within structure or nested structure
struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
struct structure1 obj;
};
2. Point out the meaning of array of structures.
Structure is collection of different data type. An object of structure represents a single record in
memory, if we want more than one record of structure type, we have to create an array of
structure or object. As we know, an array is a collection of similar type, therefore an array can be
of structure type.

Syntax for declaring structure array

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

struct struct-name var [ size ];


3. Show the difference between Structures from Array.
ARRAY STRUCTURE
Array refers to a collection consisting of Structure refers to a collection consisting of
elements of homogenous data type. elements of heterogenous data type.
Array uses subscripts or “[ ]” (square bracket) for Structure uses “.” (Dot operator) for element
element access access
Array is pointer as it points to the first element of
Structure is not a pointer
the the collection.
ARRAY STRUCTURE
Instantiation of Array objects is not possible. Instantiation of Structure objects is possible.
Array size is fixed and is basically the number of Structure size is not fixed as each element of
elements multiplied by the size of an element. Structure can be of different type and size.
Bit filed is not possible in an Array. Bit filed is possible in an Structure.
Array declaration is done simply using [] and not Structure declaration is done with the help of
any keyword. “struct” keyword.
Arrays is a primitive datatype Structure is a user-defined datatype.

4. Show an example program using union


A union is a user-defined type similar to structs in C programming.
How to define a union?
We use the union keyword to define unions. Here's an example:
1. union car
2. {
3. char name[50];
4. int price;
5. };
Creating union variable:
union car c;
5. What is structure? Write the syntax for structure.
Structure is commonly referred to as user-defined data type. Structure is similar to an array but
the only difference is that array is collection of similar data type onthe other hand structure is
collection of different data type. A structure can contain any data type including array and
another structure as well. Each variable declared inside structure is called member of structure.
Declaration of structure must start with the keyword struct followed by the structure name and
structure's member variables are declared within braces.
Syntax for declaring structure

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
Example for declaring structure
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Syntax for creating object

struct struct-name var;

6.Interpret the term Union in C.


A union is a special data type available in C that allows to store different data types in the same
memory location.
Example:
union Data {
int i;
float f;
char str[20];
} data;
7. How the members of structure object is accessed?
There are two types of operators used for accessing members of a structure.
Dot operator- Member operator
> - Structure pointer operator
8. Discover the meaning of enum.
Enumeration is a user defined datatype in C language. It is used to assign names to the integral
constants which makes a program easy to read and maintain. The keyword “enum” is used to
declare an enumeration.
Here is the syntax of enum in C language,
enum enum_name{const1, const2, ....... };

9. Invent the application of size of operator to this structure.


Consider the declaration:
struct
{
char name; int num;
} student;
int main() {
int size;
struct student s;

size = sizeof(s);
printf("nSize of Structure : %d", size);
return(0);
}
10.What is meant by Self-referential structures.
Self Referential structures are those structures that have one or more pointers which point to the
same type of structure, as their member.
Example:
struct node {
int data1;
char data2;
struct node* link;
};

11. Write the use of size operator on structure.


sizeof() operator is used to calculate the size of any variables, pointers or data types, data types
could be pre-defined or user-defined.Using the sizeof() operator we can calculate the size of the
structure straightforward to pass it as a parameter.
struct
{
char name; int num;
} student;
int main() {
int size;
struct student s;
size = sizeof(s);
printf("nSize of Structure : %d", size);
return(0);
}
12. What is a nested structure?
When a structure contains another structure, it is called nested structure. For example,we have
two structures named Address and Employee. To make Address nested to Employee, we have to
define Address structure before and outside Employee structure and create an object of Address
structure inside Employee structure.

Syntax for structure within structure or nested structure

struct structure1
{
----------
----------
};

struct structure2
{
----------
----------
struct structure1 obj;
};
13. How typedef is used in structure?
Typedef is a keyword that is used to give a new symbolic name for the existing name in a C
program. This is same like defining alias for the commands.
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
To declare structure variable, we can use the below statements.
status record1; /* record 1 is structure variable */
status record2; /* record 2 is structure variable */
14. Point out the meaning of array of structures.
C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas,
array of structures is nothing but collection of structures. This is also called as structure array in
C.
struct student
{
int id;
char name[30];
float percentage;
};

struct student record[2];


15. Mention any two ways passing structures and functions
PASSING STRUCTURE TO FUNCTION IN C BY VALUE:
The whole structure is passed to another function by value. It means the whole structure is
passed to another function with all members and their values. So, this structure can be accessed
from called function.
struct student
{
int id;
char name[20];
float percentage;
};

func(record);

PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:


The whole structure is passed to another function by address. It means only the address of the
structure is passed to another function. The whole structure is not passed to another function with
all members and their values.

struct student
{
int id;
char name[20];
float percentage;
};

func(&record);

16.Specify the use of typedef

typedef provides an alias name to the existing complex type definition. With typedef you can
simply create alias for any type. Whether it is a simple integer to complex function pointer or
structure declaration, typedef will shorten your code.
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
To declare structure variable, we can use the below statements.
status record1; /* record 1 is structure variable */
17. Generalize the operators used in access the structure members
There are two types of operators used for accessing members of a structure.

1. . - Member operator
2. -> - Structure pointer operator.
19. Discriminate copying and comparing operation on structures.
Two variables of the same structure type can be copied the same way as ordinary variables. If
persona1 and person2 belong to the same structure, then the following statements Are valid.
person1 = person2;
person2 = person1;

x = ((student3.number == student2.number) &&


(student3.marks == student2.marks)) ? 1 : 0;
20. How to differentiate structure and union?

PART B
1.Write a C program using structures to prepare the students mark statement.
#include<stdio.h>
struct student
{
int sub1;
int sub2;
int sub3;
};
void main()
{
struct student s[10];
int i,total=0;
clrscr();
for(i=0;i<=2;i++)
{
printf("\nEnter Marks in Three Subjects = ");
scanf("%d%d%d",& s[i].sub1,&s[i].sub2,&s[i].sub3);
total=s[i].sub1+s[i].sub2+s[i].sub3;
printf("\nTotal marks of s[%d] Student= %d",i,total);
}
getch();
}

2.(i) Illustrate a C program to store the employee information using structure and
search a particular employee details.
#include<stdio.h>
#include<stdlib.h>
struct details
{
char name[30];
int eid;
int salary;
}emp[5];

void emp_search(int r)
{
int id,I,find=0;
printf("\nEnter Employee-Id to be Searched : ");
scanf("%d",&id);
printf("----------------------------------------\n");
for(i=0;i<r;i++)
{
if(emp[i].eid==id)
{
find=1;
printf("Employee Id : %d",emp[i].eid);
printf("\nName : %s",emp[i].name);
printf("\nSalary : %d\n",emp[i].salary);
break;
}
}
}

If(found==0)
Printf(“The Employee not found in the list\n”);

int main()
{
int n,i,ch;
printf("/*How Many Employee Record You Want to Add*/\n\nEnter Limit : ");
scanf("\n %d",&n);
for(i=0;i<n;i++)
{
printf("-----------------------------------------");
printf("\n\tEnter Details of Employee-%d",i+1);
printf("\n-----------------------------------------");
printf("\nName of Employee : ");
scanf("%s",emp[i].name);
printf("Employee-Id : ");
scanf("%d",&emp[i].eid);
printf("Salary : ");
scanf("%d",&emp[i].salary);
}
emp_search(n);

getch();
return 0;
}
ii) Discuss about the following :-
(i).Structure.
Structures:
Structure is commonly referred to as user-defined data type. Structure is similar to an array but
the only difference is that array is collection of similar data type onthe other hand structure is
collection of different data type. A structure can contain any data type including array and
another structure as well. Each variable declared inside structure is called member of structure.
Declaration of structure must start with the keyword struct followed by the structure name and
structure's member variables are declared within braces.
Syntax for declaring structure

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

(ii).Union.
A union is a special data type available in C that allows to store different data types in the same
memory location. You 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.

#include<stdio.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{

struct Employee E; //Statement 1

printf("\nEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\nEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\nEnter Employee Age : ");


scanf("%d",&E.Age);

printf("\nEnter Employee Salary : ");


scanf("%ld",&E.Salary);

printf("\n\nEmployee Id : %d",E.Id);
printf("\nEmployee Name : %s",E.Name);
printf("\nEmployee Age : %d",E.Age);
printf("\nEmployee Salary : %ld",E.Salary);

Output :

Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000

Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Defining a Union

To define a union, you must use the union statement in the same way as you 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 −

#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;


printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
When the above code is compiled and executed, it produces the following result −memory size
occupied by data : 20

3. Define a structure called student that would contain name, regno and marks of
five subjects and percentage. Write a program to read the details of name, regno and
marks of five subjects for 30 students, calculate the percentage and display the
name, regno, marks of the subjects and percentage of each student
Refer class notes
3.Describe about the functions and structures.
We can pass the C structures to functions in 3 ways:
1.Passing each individual item of the structure as a function argument. This is similar to passing
normal values as arguments. Although it is easy to implement, we don’t use this approach
because if the size of a structure is bit larger, then our life become miserable.
2.Passing the whole structure as a value.
3 Pass the address of the structure (pass by reference).

2.PASSING STRUCTURE TO FUNCTION IN C BY VALUE:


In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can
be accessed from called function. This concept is very useful while writing very big programs in
C.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
3.PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:
In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to
another function with all members and their values. So, this structure can be accessed from
called function by its address.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
4. Demonstrate about structures, array of structures and nested structures.
Structure is commonly referred to as user-defined data type. Structure is similar to an array but
the only difference is that array is collection of similar data type onthe other hand structure is
collection of different data type. A structure can contain any data type including array and
another structure as well. Each variable declared inside structure is called member of structure.

Declaration of structure must start with the keyword struct followed by the structure name and
structure's member variables are declared within braces.

Syntax for declaring structure

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

Example for declaring structure

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Accessing the structure members

We have to create an object of structure to access its members. Object is a variable of type
structure. Structure members are accessed using the dot operator(.) between structure's object and
structure's member name.

Syntax for creating object

struct struct-name obj;

Example for creating object & accessing structure members

#include<stdio.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{

struct Employee E; //Statement 1

printf("\nEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\nEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\nEnter Employee Age : ");


scanf("%d",&E.Age);

printf("\nEnter Employee Salary : ");


scanf("%ld",&E.Salary);

printf("\n\nEmployee Id : %d",E.Id);
printf("\nEmployee Name : %s",E.Name);
printf("\nEmployee Age : %d",E.Age);
printf("\nEmployee Salary : %ld",E.Salary);

Output :

Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000

Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Array of Structure

Structure is collection of different data type. An object of structure represents a single record in
memory, if we want more than one record of structure type, we have to create an array of
structure or object. As we know, an array is a collection of similar type, therefore an array can be
of structure type.

Syntax for declaring structure array

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

struct struct-name var [ size ];

Example for declaring structure array

#include<stdio.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{
int i;
struct Employee Emp[ 3 ]; //Statement 1

for(i=0;i<3;i++)
{

printf("\nEnter details of %d Employee",i+1);

printf("\n\tEnter Employee Id : ");


scanf("%d",&Emp[i].Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&Emp[i].Name);

printf("\n\tEnter Employee Age : ");


scanf("%d",&Emp[i].Age);
printf("\n\tEnter Employee Salary : ");
scanf("%ld",&Emp[i].Salary);
}

printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :

Enter details of 1 Employee


Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000

Enter details of 2 Employee


Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000

Enter details of 3 Employee


Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000

Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000

In the above example, we are getting and displaying the data of 3 employee using array of object.
Statement 1 is creating an array of Employee Emp to store the records of 3 employees.

Nested Structure in C
When a structure contains another structure, it is called nested structure. For example,we have
two structures named Address and Employee. To make Address nested to Employee, we have to
define Address structure before and outside Employee structure and create an object of Address
structure inside Employee structure.
Syntax for structure within structure or nested structure

struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
struct structure1 var;
};
Example for structure within structure or nested structure

#include<stdio.h>

struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};

void main()
{
int i;
struct Employee E;

printf("\n\tEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\n\tEnter Employee Salary : ");


scanf("%f",&E.Salary);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.HouseNo);

printf("\n\tEnter Employee City : ");


scanf("%s",&E.Add.City);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.PinCode);

printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);

Output :

Enter Employee Id : 101


Enter Employee Name : Suresh
Enter Employee Salary : 45000
Enter Employee House No : 4598/D
Enter Employee City : Delhi
Enter Employee Pin Code : 110056

Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056
5.Write a C program using structures to prepare the employee pay roll of a company.

#include<stdio.h>
#include<conio.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
} e[10] ;
void main()
{
int i, n ;
clrscr() ;
printf("Enter the number of employees : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the employee number : ") ;
scanf("%d", &e[i].empno) ;
printf("\nEnter the name : ") ;
scanf("%s", e[i].name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &e[i].bpay, &e[i].allow, &e[i].ded) ;
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", e[i].empno,
e[i].name, e[i].bpay, e[i].allow, e[i].ded, e[i].npay) ;
}
getch() ;
}
Output:
Enter the number of employees : 2
Enter the employee number : 101
Enter the name : Arun
Enter the basic pay, allowances & deductions : 5000 1000 250
Enter the employee number : 102
Enter the name : Babu
Enter the basic pay, allowances & deductions : 7000 1500 750
Emp.No. Name Bpay Allow Ded Npay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750
6. (i).What is a structure? Express a structure with data members of various types
and declare two structure variables. Write a program to read data into these and
print the same.
struct student
{
char name[50];
int roll;
float marks;
} s,d;
int main()
{
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Enter name: ");
scanf("%s", d.name);
printf("Enter roll number: ");
scanf("%d", &d.roll);
printf("Enter marks: ");
scanf("%f", &d.marks);
printf("Displaying Information:\n");
printf("Name: ");
puts(s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %.1f\n", s.marks);
printf("Name: ");
puts(d.name);
printf("Roll number: %d\n",d.roll);
printf("Marks: %.1f\n", d.marks);
return 0;
}
Output
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5
Enter name: Kavin
Enter roll number: 27
Enter marks: 74.5
Displaying Information:
Name: kavin
Roll number: 27
Marks: 74.5

(ii) Justify the need for structured data type.


A structure is a user defined data type in C/C++. A structure creates a data type that can be used
to group items of possibly different types into a single type.
struct’ keyword is used to create a structure. Following is an example.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

initialize structure members


struct Point
{
int x, y;
};

int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
access structure elements?
Structure members are accessed using dot (.) operator.

#include<stdio.h>

struct Point
{
int x, y;
};

int main()
{
struct Point p1 = {0, 1};

// Accesing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);

return 0;
}

array of structures
Like other primitive data types, we can create an array of structures.
#include<stdio.h>

struct Point
{
int x, y;
};

int main()
{
// Create an array of structures
struct Point arr[10];

// Access array members


arr[0].x = 10;
arr[0].y = 20;

printf("%d %d", arr[0].x, arr[0].y);


return 0;
}
Output:
10 20
7.Explain about the structures and its operations
Structure is a user-defined datatype in C language which allows us to combine data of different
types together.

Defining a structure
struct keyword is used to define a structure. struct defines a new data type which is a collection
of primary and derived datatypes.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
Example:
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};

struct Student S1, S2; //declaring variables of struct Student

Example:
#include<stdio.h>

struct Student
{
char name[10];
int roll;
};

void show(struct Student st);

void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
void show(struct Student st)
{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}
In C, the only operation that can be applied to struct variables is assignment. Any other operation
(e.g. equality check) is not allowed on struct variables.
For example, program 1 works without any error.

#include <stdio.h>

struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p2
printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);
getchar();
return 0;
}
Output:
p2.x = 10, p2.y = 20

7.Write a C program using structures to prepare the students mark statement.


Refer class notes
8. Write a C program to read the details of book name, author name and price of 200
books in a library and display the total cost of the books and the book details whose price is
above Rs.500.

#include<stdio.h>

#include<conio.h>

#include<string.h>

#define SIZE 200


struct bookdetail

char name[20];

char author[20];

int pages;

float price;

};

void output(struct bookdetail v[],int n);

void main()

struct bookdetail b[SIZE];

int n,i;

clrscr();

printf("Enter the Numbers of Books:");

scanf("%d",&n);

printf("\n");

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

printf("\t=:Book %d Detail:=\n",i+1);

printf("\nEnter the Book Name:\n");

scanf("%s",b[i].name);

printf("Enter the Author of Book:\n");

scanf("%s",b[i].author);
printf("Enter the Pages of Book:\n");

scanf("%d",&b[i].pages);

printf("Enter the Price of Book:\n");

scanf("%f",&b[i].price);

output(b,n);

getch();

void output(struct bookdetail v[],int n)

int i,t=1;

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

If(b[i].price>500)

{ printf("\n");

printf("Book No.%d\n",t);

printf("\t\tBook %d Name is=%s \n",t,v[i].name);

printf("\t\tBook %d Author is=%s \n",t,v[i].author);

printf("\t\tBook %d Pages is=%d \n",t,v[i].pages);

printf("\t\tBook %d Price is=%f \n",t,v[i].price);

printf("\n");

}
}

9.Explain nested structure and write C Program to Implement the same. (13)
The structure can be nested in the following ways.

1. By separate structure
2. By Embedded structure

The structure can be nested in the following ways.

1. By separate structure
2. By Embedded structure

1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main
structure as a member. Consider the following example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in
Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence, it requires
less line of codes but it can not be used in multiple data structures. Consider the following
example.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Accessing Nested Structure
We can access the member of the nested structure by Outer_Structure.Nested_Structure.member
as given below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
C Nested Structure example
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n",
e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
10. Define a structure called student that would contain name, regno and marks of five
subjects and percentage. Write a program to read the details of name, regno and marks of
five subjects for 30 students, calculate the percentage and display the name, regno, marks
of the subjects and percentage of each student(13)
Refer class notes
11. Explain with an example the self-referential structure. (13)
A self referential structure is used to create data structures like linked lists, stacks, etc. Following
is an example of this kind of structure:

struct struct_name
{
datatype datatypename;
struct_name * pointer_name;
};

A self-referential structure is one of the data structures which refer to the pointer to (points) to
another structure of the same type. For example, a linked list is supposed to be a self-referential
data structure. The next node of a node is being pointed, which is of the same struct type. For
example,
A linear linked list is a chain of structures where each node points to the next node to create a
list. To keep track of the starting node's address a dedicated pointer (referred as start pointer)
is used. The end of the list is indicated by a NULL pointer. In order to create a linked list of
integers, we define each of its element (referred as node) using the following declaration.
struct node_type {
int data;
struct node_type *next;
};
struct node_type *start = NULL;
Note: The second member points to a node of same type.
Example
Let us now develop a C program to manipulate linked lists. For this purpose we introduce a
few basic functions, which can be used to create a list, displaying its contents, inserting into a
list and deleting an existing element. We also introduce two
functions reverse and recReverse for reversing the elements of the list.
When a list is created a pointer called start is used to indicate the beginning of the list. A
function createNode, creates a node and returns a pointer to it. The function insert is used to
insert a new node in an existing list provided the data is not already present in the list. If it is
not present, we place the data in a manner so that the new element is appended at the end of
the list.

12(i) .Does structure bring additional overhead to a program? Justify. (7)

Structured Datatypes

 A structure in C is a collection of items of different types.


Structure bring additional overhead to a program:

 There an additional Overhead to Retrieve an Element in a Struct.


 structures slower than arrays
 not allowing all operations on struct.
 Parameter passing and returning using struct additional overhead.
Example:
In C, the only operation that can be applied to struct variables is assignment. Any other
operation (e.g. equality check) is not allowed on struct variables.
For example, program 1 works without any error and program 2 fails in compilation.
Program 1
#include <stdio.h>

struct Point {
int x;
int y;
};

int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p1
printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);
getchar();
return 0;
}

Output:

p2.x = 10, p2.y = 20

Program 2
#include <stdio.h>

struct Point {
int x;
int y;
};

int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p1
if (p1 == p2) // compiler error: cannot do equality check for
// whole structures
{
printf("p1 and p2 are same ");
}
getchar();
return 0;
}

(ii). Write short note on structure declaration(6)


A "structure declaration" names a type and specifies a sequence of variable values (called
"members" or "fields" of the structure) that can have different types. An optional
identifier, called a "tag," gives the name of the structure type and can be used in
subsequent references to the structure type. A variable of that structure type holds the
entire sequence defined by that type. Structures in C are similar to the types known as
"records" in other languages.
Syntax
The general syntax for a struct declaration in C is:

struct tag_name {
type member1;
type member2;
……………};

Such a struct declaration may also appear in the context of a typedef declaration of a type
alias or the declaration or definition of a variable:

typedef struct tag_name {


type member1;
type member2;
-------------
} struct_alias;

Nested structures can also be accessed as though they were declared at the file-scope
level. For example, given this declaration:
struct a
{
int x;
struct b
{
int y;
} var2;
} var1;

these declarations are both legal:


struct a var3;
struct b var4;
Example:
#include <stdio.h>
struct student {
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
};

Void main()
{
struct student student_a;

strcpy(student_a.firstName, "Deo");
strcpy(student_a.lastName, "Dum");
strcpy(student_a.SSN, "2333234" );
student_a.gpa = 2009.20;

printf( "First Name: %s\n", student_a.firstName );


printf( "Last Name: %s\n", student_a.lastName );
printf( "SNN : %s\n", student_a.SSN );
printf( "GPA : %f\n", student_a.gpa );
}
Output
First Name: Deo
Last Name: Dum
SSN : 2333234
GPA : 2009.20

PART-C
1.Write a structure to store the name, account number and balance of customers (more
than 10) and store their information. Write a function to print the names of all the
customers having balance less than $200
#include<stdio.h>
#include<conio.h>

struct bank
{
int acc_no;
char name[20];
int bal;
};
void bal_check(struct bank b[],int);

void main()
{
Struct bank b[15];
int i,n;

clrscr();
printf("Enter total customers\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" \n enter the acc_no,name,balance");
printf("\nenter the account no");
scanf("%d",&b[i].acc_no);
printf("\n enter the name");
scanf("%s",b[i].name);
printf("\n enter the balance");
scanf("%d",&b[i].bal);
}

bal_check(b,n);

getch();

}
void bal_check(struct bank b[],int n)
{
int i;
for(i=0;i<n;i++)
if(b[i].bal<200)
{
printf("\n---------------------------------------------\n");
printf("\n The acc_no,name,balance below RS:-100");
printf("\n the account no:-%d",b[i].acc_no);
printf("\n the name:-%s",b[i].name);
printf("\n the balance:-%d",b[i].bal);
}
}

2. Compare and contrast between Structures and Unions


1. Both are user-defined data types used to store data of different types as a single unit.
2. Their members can be objects of any type, including other structures and unions or arrays.
A member can also consist of a bit field.
3. Both structures and unions support only assignment = and sizeof operators. The two
structures or unions in the assignment must have the same members and member types.
4. A structure or a union can be passed by value to functions and returned by value by
functions. The argument must have the same type as the function parameter. A structure or
union is passed by value just like a scalar variable as a corresponding parameter.
5. ‘.’ operator is used for accessing members.
Differences
// declaring structure
struct struct_example
{
int integer;
float decimal;
char name[20];
};

// declaraing union

union union_example
{
int integer;
float decimal;
char name[20];
};

3.Examine the differences between nested structures and array of structures.


Nested Structure:
When a structure contains another structure, it is called nested structure. For example,we have
two structures named Address and Employee. To make Address nested to Employee, we have to
define Address structure before and outside Employee structure and create an object of Address
structure inside Employee structure.
Syntax for structure within structure or nested structure

struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
struct structure1 var;
};
Example for structure within structure or nested structure

#include<stdio.h>

struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};

void main()
{
int i;
struct Employee E;

printf("\n\tEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\n\tEnter Employee Salary : ");


scanf("%f",&E.Salary);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.HouseNo);

printf("\n\tEnter Employee City : ");


scanf("%s",&E.Add.City);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.PinCode);

printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);

Output :

Enter Employee Id : 101


Enter Employee Name : Suresh
Enter Employee Salary : 45000
Enter Employee House No : 4598/D
Enter Employee City : Delhi
Enter Employee Pin Code : 110056

Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056

Array of Structure

Structure is collection of different data type. An object of structure represents a single record in
memory, if we want more than one record of structure type, we have to create an array of
structure or object. As we know, an array is a collection of similar type, therefore an array can be
of structure type.

Syntax for declaring structure array

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

struct struct-name var [ size ];

Example for declaring structure array

#include<stdio.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
int i;
struct Employee Emp[ 3 ]; //Statement 1

for(i=0;i<3;i++)
{

printf("\nEnter details of %d Employee",i+1);

printf("\n\tEnter Employee Id : ");


scanf("%d",&Emp[i].Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&Emp[i].Name);

printf("\n\tEnter Employee Age : ");


scanf("%d",&Emp[i].Age);

printf("\n\tEnter Employee Salary : ");


scanf("%ld",&Emp[i].Salary);
}

printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :

Enter details of 1 Employee


Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000

Enter details of 2 Employee


Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000

Enter details of 3 Employee


Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000

Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000

4.Develop a C Program to use the arrays inside union variables

Unions are Declared in the same way as a Structure.Only “struct Keyword” is replaced with
union

Sample Declaration of Union :

union stud
{
int roll;
char name[4];
int marks;
}s1;

To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type. The
following example shows how to use unions in a program −

#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

return 0;
}

When the above code is compiled and executed, it produces the following result −

data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.

You might also like