Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 4 Qba PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

UNIT 4

PART-A

1. What is structure? Write the syntax for structure.


Structure is a collection of variables of different types under a single name.
Syntax of structure
structstructure_name
{
data_type member1;
data_type member2;
.
.
};

2. Where is Union used in C?


The primary use of a union is allowing access to a common location by different data
types, for example hardware input/output access, bitfield and word sharing.

3. How the members of structure object is accessed?


The members of a structure object can be accessed by using:
1. Direct member access operator (i.e. ., also known as dot operator).
2. Indirect member access operator (i.e. ‐>, also known as arrow operator).

4. How many bytes in memory taken by the following C structure?


#include <stdio.h>
struct test
{ int k;
char c;
};

Ans:3 bytes

5. What is a nested structure?


A structure can be nested within another structure.

6. How typedef is used in structure?


typedef can be used to create an alias for the desired structure type so that the
keywordstruct is notrequired repeatedly to declare the structure objects.
Example: struct name
{
charfirst_name[30];
charlast_name[30];
}
typedefstruct name name;
Here, typedef name is same as structure‐tag name. The object for the structure name can
now bedeclared as
name person;
instead of
struct name person;

7. Interpret the term Union in C.


A union is a collection of one or more variables, possibly of different types. In union, all
the members of an object share the same memory. The amount of memory allocated to it
is the amount necessary to contain its largest member.but only one member can contain a
value at any given time.

8. What is mean by Self referential structures.


A self referential data structure is essentially a structure definition which includes at least
one member that is a pointer to the structure of its own kind. A chain of such structures
can thus be expressed as follows.
struct name {
member 1;
member 2;
...
struct name *pointer;
};

9. Point out the meaning of Dynamic memory allocation.


Dynamic memory management refers to memory management at run time. This allows
you to obtain more memory when required and release it when not necessary.
<stdlib.h> for dynamic memory allocation.

Function Use of Function


malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

10. Can we compare two structures in C? Justify.


Comparing structures in c is not permitted to check or compare directly with logical
operators. Only structure members can be comparable with logical operator.

11. Specify the use of typedef.


typedef can be used to create an alias for the desired structure type so that the keyword
struct is notrequired repeatedly to declare the structure objects.
12. Can Union be nested in structure?
A union can be nested in a structure.

13. Discover the meaning of enum.


As the name suggests Enumerated data type helps the users in creating their own
identifiers.
Syntax :
enumEnum-identifier(value1,value2..value N)
Eg: enumdays(Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday)

14. Show the difference between Structures from Array.


Arrays Structures
1. An array is a collection of related data 1. Structure can have elements of
elements of the same type. different types
2. An array is a derived data type 2. A structure is a programmer-
defined data type
3. Any array behaves like a built-in data 3. But in the case of structure, first,
types. All we have to do is to declare an we have to design and declare a data
array variable and use it. structure before the variable of that
type are declared and used.
4. Array allocates static memory and 4. Structures allocate dynamic
uses index/subscript for accessing memory and uses (.) operator for
elements of the array. accessing the member of a structure.
5. An array is a pointer to the first
5. Structure is not a pointer
element of it

15. Invent the application of size of operator to this structure. Consider the
declaration:
struct
{
char name;
intnum;
} student;
Ans.: Size of operator to this structure is 3 bytes.

16. Is it mandatory that the size of all elements in a union should be same?
No.The standard only guarantee that the size of a union is sufficient for the largest
member, i.e, not necessarily the same size.
17. Develop a structure namely Book and create array of Book structure with size of
ten.
struct Book
{
char book_title[20];
char author[20];
int cost;
};
int count;
struct Book b[10];

18. What will be the output of the C program?


#include<stdio.h>
int main()
{ enum numbers{n1 = 1.5, n2 = 0, n3, n4, n5, n6};
printf("%d %d\n", n1, n2);
}
Ans.: error: enumerator value for ‘n1’ is not an integer constant

19. What is the difference between enum and macro?


• Enumeration is a type of integer.
• Macros can be of any type. Macros can even be any code block containing
statements, loops, function calls etc.

20. Can we declare function inside structure of C programming? Justify.


No.BecauseC standard does not allow to declare function/method inside a structure. C is
not object-oriented language.

PART – B

1 Describe about the functions and structures. (13)

Functions

• A function is a group of statements that together perform a task.


• A function declaration tells the compiler about a function's name, return type, and
parameters.
• A function definition provides the actual body of the function.
Defining a Function

The general form of a function definition in C programming language is as follows −


return_typefunction_name( parameter list ){
bodyof the function
}

A function definition in C programming consists of a function header and a function


body. Here are all the parts of a function −

• Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
• Function Body − The function body contains a collection of statements that define
what the function does.

Example

Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two −

/* function returning the max between two numbers */


int max(int num1,int num2){

/* local variable declaration */


int result;

if(num1 > num2)


result= num1;
else
result= num2;

return result;
}
Structure:
structure is user defined data type available in C that allows to combine data items of
different kinds.
Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member. The format of the struct statement is as
follows −
struct[structure tag]{

member definition;
member definition;
...
member definition;
}[one or more structure variables];

The structure 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 structure's
definition, before the final semicolon, you can specify one or more structure variables but
it is optional. Here is the way you would declare the Book structure −

structBooks{
char title[50];
char author[50];
char subject[100];
intbook_id;
} book;
Accessing Structure Members

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

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

structBooks{
char title[50];
char author[50];
char subject[100];
intbook_id;
};

int main(){

structBooksBook1;/* Declare Book1 of type Book */

/* book 1 specification */
strcpy(Book1.title,"C Programming");
strcpy(Book1.author,"Nuha Ali");
strcpy(Book1.subject,"C Programming Tutorial");
Book1.book_id =6495407;
/* print Book1 info */
printf("Book 1 title : %s\n",Book1.title);
printf("Book 1 author : %s\n",Book1.author);
printf("Book 1 subject : %s\n",Book1.subject);
printf("Book 1 book_id : %d\n",Book1.book_id);

return0;
}

2. Explain about the structures and its operations. (13)


Structure:
structure is user defined data type available in C that allows to combine data items
of different kinds.
Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member. The format of the struct statement is as
follows −

struct[structure tag]{

member definition;
member definition;
...
member definition;
}[one or more structure variables];

The structure 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 structure's definition, before the final semicolon, you can specify one or more
structure variables but it is optional. Here is the way you would declare the Book
structure −

structBooks{
char title[50];
char author[50];
char subject[100];
intbook_id;
} book;
Accessing Structure Members

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

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

structBooks{
char title[50];
char author[50];
char subject[100];
intbook_id;
};

int main(){

structBooksBook1;/* Declare Book1 of type Book */

/* book 1 specification */
strcpy(Book1.title,"C Programming");
strcpy(Book1.author,"Nuha Ali");
strcpy(Book1.subject,"C Programming Tutorial");
Book1.book_id =6495407;

/* print Book1 info */


printf("Book 1 title : %s\n",Book1.title);
printf("Book 1 author : %s\n",Book1.author);
printf("Book 1 subject : %s\n",Book1.subject);
printf("Book 1 book_id : %d\n",Book1.book_id);

return0;
}

3. Explain about array of structures and nested structureswith example.(13)

Array of Structures: It is possible to create an array whose elements are of structure type.
Such an array is known as array of structures.
ARRAY OF STRUCTURES

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

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

int main()
{
int i;
struct student record[2];

// 1st student's record


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

// 2nd student's record


record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;

// 3rd student's record


record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;

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


{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}

OUTPUT:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000

Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000

• Nested Structure

Nested structure in c language can have another structure as a member.

Let's see the code of nested structure.

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.

Accessing Nested Structure

We can access the member of nested structure by


Outer_Structure.Nested_Structure.member as given below:

1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy
4. Write a C program using structures to prepare the students mark statement. (13)
#include<stdio.h>
#include<conio.h>
structmark_sheet{
char name[20];
long introllno;
int marks[10];
int total;
float average;
char rem[10];
char cl[20];
}students[100];
int main(){
inta,b,n,flag=1;
char ch;
clrscr();
printf("How many students : \n");
scanf("%d",&n);
for(a=1;a<=n;++a){
clrscr();
printf("\n\nEnter the details of %d students : ", n-a+1);
printf("\n\nEnter student %d Name : ", a);
scanf("%s", students[a].name);
printf("\n\nEnter student %d Roll Number : ", a);
scanf("%ld", &students[a].rollno);
students[a].total=0;
for(b=1;b<=5;++b){
printf("\n\nEnter the mark of subject-%d : ", b);
scanf("%d", &students[a].marks[b]);
students[a].total += students[a].marks[b];
if(students[a].marks[b]<40)
flag=0;
}
students[a].average = (float)(students[a].total)/5.0;
if((students[a].average>=75)&&(flag==1))
strcpy(students[a].cl,"Distinction");
else
if((students[a].average>=60)&&(flag==1))
strcpy(students[a].cl,"First Class");
else
if((students[a].average>=50)&&(flag==1))
strcpy(students[a].cl,"Second Class");
else
if((students[a].average>=40)&&(flag==1))
strcpy(students[a].cl,"Third Class");
if(flag==1)
strcpy(students[a].rem,"Pass");
else
strcpy(students[a].rem,"Fail");
flag=1;
}
for(a=1;a<=n;++a){
clrscr();
printf("\n\n\t\t\t\tMark Sheet\n");
printf("\nName of Student : %s", students[a].name);
printf("\t\t\t\t Roll No : %ld", students[a].rollno);
printf("\n------------------------------------------------------------------------");
for(b=1;b<=5;b++){
printf("\n\n\t Subject %d \t\t :\t %d", b, students[a].marks[b]);
}
printf("\n\n------------------------------------------------------------------------ \n");
printf("\n\n Totl Marks : %d", students[a].total);
printf("\t\t\t\t Average Marks : %5.2f", students[a].average);
printf("\n\n Class : %s", students[a].cl);
printf("\t\t\t\t\t Status : %s", students[a].rem);
printf("\n\n\n\t\t\t\t Press Y for continue . . . ");
ch = getche();
if((ch=="y")||(ch=="Y"))
continue;
}
return(0);
}
Output:
How many students : 2
Enter the details of 2 students :
Enter student 1 Name : H.Xerio
Enter student 1 Roll Number : 536435
Enter the mark of subject-1 : 46
Enter the mark of subject-1 : 56
Enter the mark of subject-1 : 76
Enter the mark of subject-1 : 85
Enter the mark of subject-1 : 75
Enter the details of 1 students :
Enter student 1 Name : K.Reriohe
Enter student 1 Roll Number : 237437
Enter the mark of subject-1 : 36
Enter the mark of subject-1 : 52
Enter the mark of subject-1 : 66
Enter the mark of subject-1 : 45
Enter the mark of subject-1 : 74

Mark Sheet
Name of Student : H.Xerio Roll No : 536435
------------------------------------------------------------------------
subject 1 : 46
subject 2 : 56
subject 3 : 76
subject 4 : 85
subject 5 : 75
------------------------------------------------------------------------
Total Marks : 338 Average Marks : 67.6
Class : First Class Status : Pass

5. Write a C program to add two distances in feet and inches using structure (13)
#include<stdio.h>
struct Distance {
int feet;
float inch;
} d1, d2, sumOfDistances;

int main() {
printf("Enter information for 1st distance\n");
printf("Enter feet: ");
scanf("%d", &d1.feet);
printf("Enter inch: ");
scanf("%f", &d1.inch);
printf("\nEnter information for 2nd distance\n");
printf("Enter feet: ");
scanf("%d", &d2.feet);
printf("Enter inch: ");
scanf("%f", &d2.inch);

sumOfDistances.feet=d1.feet+d2.feet;
sumOfDistances.inch=d1.inch+d2.inch;

// If inch is greater than 12, changing it to feet.


if (sumOfDistances.inch>12.0) {
sumOfDistances.inch = sumOfDistances.inch-12.0;
++sumOfDistances.feet;
}
printf("\nSum of distances = %d\'-%.1f\"", sumOfDistances.feet, sumOfDistances.inch);
return 0;
}
6. 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. (13)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void book_cost();
void disp_book();
void read_book();

struct book
{
char book_title[20];
char author[20];
int cost;
};
int count;
struct book b[200];

void main()
{
intch;
while(1)
{
clrscr();
printf("\n 1:Read book \n");
printf("\n 2:Total cost of the books \n");
printf("\n 3:Display books \n");
printf("\n 4:exit \n");
printf("\n\n enter the choice \n");
scanf("%d",&ch);
switch(ch)
{
case 1: read_book(); getch();
break;
case 2: book_cost(); getch();
break;
case 3: disp_book(); getch();
break;
case 4:exit(0);
}
}
}

void read_book()
{

for(count=0;count<200;count++) {
printf("\n enter book detail ");
printf("\n enter name of book\n");
scanf("%s",b[count].book_title);
printf("\n enter name of author\n");
scanf("%s",b[count].author);
printf("\n enter book cost \n");
scanf("%d",&b[count].cost);
}
}

void disp_book()
{
int i;
printf("\n detail of %d book ",count);
for(i=0;i<200;i++)
{
printf("\n %s\n%s\n%d",b[i].book_title,b[i].author,b[i].cost);
}

printf("\n Detail of books above Rs.500 ",count);


for(i=0;i<200;i++)
{if (b[i].cost >500)
printf("\n %s\n%s\n%d",b[i].book_title,b[i].author,b[i].cost);
}

void book_cost()
{
intI,p=0;
for(i=0;i<200;i++)
{
p=p+b[i].cost;
{
printf("\nTotal cost %d",p);
}
}
}

7. (i) 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. (8)
#include <stdio.h>
struct student {
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
};

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

(ii) Justify the need for structured data type.(5)


• A structure in C is a collection of items of different types. You can think of a
structure as a "record" is in Pascal or a class in Java without methods.
• Structures, or structs, are very useful in creating data structures larger and more
complex.
• Simply you can group various built-in data types into a structure.
• Object conepts was derived from Structure concept. You can achieve few object
oriented goals using C structure but it is very complex.

8. (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 usingstruct 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>

structPoint {
intx;
inty;
};

intmain()
{
structPoint p1 = {10, 20};
structPoint p2 = p1; // works: contents of p1 are copied to p1
printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);
getchar();
return0;
}
Program 2
#include <stdio.h>

structPoint {
intx;
inty;
};

intmain()
{
structPoint p1 = {10, 20};
structPoint 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();
return0;
}

(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{

typemember1;

typemember2;

……………};

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

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

9. (i).How to access enumerated datatype and explain with an example program.(7)


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,

enumenum_name{const1, const2, ....... };


#include<stdio.h>
EXAMPLE:

enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};


enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed,
Thur, Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues,
Wedn, Thurs, Frid, Satu, Sund);
return 0;
}
Output
The value of enum week: 10 11 12 13 10 16 17
The default value of enum day: 0 1 2 3 1811 12

(ii) Create enum of week days. Write a program in C, use this enum and display it.
(6)
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed,
Thur, Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues,
Wedn, Thurs, Frid, Satu, Sund);
return 0;
}
Output
The value of enum week: 10 11 12 13 10 16 17
The default value of enum day: 0 1 2 3 18 11 12

10. Explain with an example the self-referential structure. (13)


A structure that contains pointers to a structure of its own type is known as self-
referential structure.

struct tag
{
member 1;
member 2;
…………
…………
struct tag *name;
};

The structure of type tag contains a member, ‘name’ which is a pointer to structure of
type tag . Thus tag is a self referential structure.

Self Referential Structure Example

struct node

int data;

struct node *link;


};

Self-referential structures have their applications in Advanced Data Structures like,


Linked Lists, Binary Trees etc..

Example Program:

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void create();
voidinsert_atfirst();
voidinsert_atlast();
void insert();
voiddelete_bypos();
voiddelete_byval();
void display();
int menu();
struct node
{
int data;
struct node *next;
}*first=NULL,*last=NULL,*temp=NULL;
void main()
{
intch;
clrscr();
do{
ch=menu();

switch(ch)
{
case 1:create();
break;
case 2:insert_atfirst();
break;
case 3:insert_atlast();
break;
case 4:insert();
break;
case 5:delete_bypos();
break;
case 6:delete_byval();
break;
case 7:display();
break;
case 8:exit(0);
case 9:clrscr();
default:printf("\nError-->Enter a valid choice!!");
exit(0);
}
}while(1);
}

11. Explain nested structure and write C Program to Implement the same. (13)

A structure can be nested within another structure.

Let's see the code of nested structure.

struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
Accessing Nested Structure

We can access the member of nested structure by


Outer_Structure.Nested_Structure.member as given below:

1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
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.pin,emp.add.phone);
}

12. Compare with example code for Structure and Union. (13)
Similarities between Structure and Union
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
structstruct_example
{
int integer;
float decimal;
char name[20];
};

// declaraing union

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

13. Illustrate a C program to store the employee information using structure and search
a particular employee details.(13)
• Define a structure called emp that would contain name, empno and
pay,allow and ded of n employees. Read the details of n employees and
calculated the net pay and display theemployee details.
• In this program, also read a particular employee no and search the employee
no .
• If it is found, display the details otherwise display not found.
The program to store details of an employee in a structure.

#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,no,f=1;
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) ;
}

printf("\nEnter the employee number to be search: ") ;


scanf("%d", &no) ;

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


{
if(e[i].empno==no)
{
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) ;
f=0;
}
}
if (f==1)
{ printf("not found”); }
getch() ;
}

14. Define a structure called student that would contain name, regno and marks of five
subjects and percentage. Write a C program to read the details of name, regno and
marks of five subjects for 30 students and calculate the percentage and display the
name, regno, marks of 30 subjects and percentage of each student.(13)
#include<stdio.h>
#include<conio.h>
struct stud{
char name[20];
long int rno;
int marks[5];
intp;

}students[30];
void calcpercentage(int);
int main(){
int a,b,j;
clrscr();
for(a=0;a<30;++a){
clrscr();
printf("\n\nEnter the details of %d student : ", a+1);
printf("\n\nEnter student %d Name : ", a);
scanf("%s", students[a].name);
printf("\n\nEnter student %d Reg Number : ", a);
scanf("%ld", &students[a].rno);
for(b=0;b<=4;++b){
printf("\n\nEnter the mark of subject-%d : ", b+1);
scanf("%d", &students[a].marks[b]);
}
}
}
calcpercentage(30);
for(a=0;a<30;++a){
clrscr();
printf("\n\n\t\t\t\tMark Sheet\n");
printf("\nName of Student : %s", students[a].name);
printf("\t\t\t\t Reg No : %ld", students[a].rno);
printf("\n------------------------------------------------------------------------");
printf("\n\n\t Percentage \t\t :\t %d", students[a].p);
}
printf("\n\n------------------------------------------------------------------------\n");
getch();
}
return(0);
}

void calcpercentage(int n)
{
int a,b,j,total;
for(a=1;a<=n;++a){
total=0;
for(j=0;j<=4;++j){
total += students[a].marks[j];
}
students[a].p=total/5;
}
}
}
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.(15)
#include<stdio.h>
/* Defining Structre*/
struct bank
{
int acc_no;
char name[20];
int bal;
}b[15];
/*Function to find the details of customer whose balance <200.*/
void check(struct bank b[],int n) /*Passing Array of structure to function*/
{
int i;
printf("\nCustomer Details whose Balance <200 Rs. \n");
printf("----------------------------------------------\n");
for(i=0;i<n;i++)
{
if(b[i].bal<200)
{
printf("Account Number : %d\n",b[i].acc_no);
printf("Name : %s\n",b[i].name);
printf("Balance : %d\n",b[i].bal);
printf("------------------------------\n");
}
}
}
int main()
{
int i;
for(i=0;i<15;i++)
{
printf("Enter Details of Customer %d\n",i+1);
printf("------------------------------\n");
printf("Enter Account Number : ");
scanf("%d",&b[i].acc_no);
printf("Enter Name : ");
scanf("%s",b[i].name);
printf("Enter Balance : ");
scanf("%d",&b[i].bal);
printf("------------------------------\n");
}
check(b,15); //call function check
return 0;
}

2. Write a C program using structures to prepare the employee pay roll of a company.
(13)
#include<stdio.h>
#include<conio.h>
Struct employee
{
char ename[30];
int eno;
float bsal;
};
void main()
{
Struct employee emp;
char name[30];
int id;
float basic,hra,da,tds,net,gross;
clrscr();
printf("\EMPLOYEE PAYROLL PROCESSING\n");
printf("\----------------------------\n");
printf("DETAILS OF THE EMPLOYEE\n");
printf("Enter the Employee Name: ");
scanf("%s",emp.ename);
strcpy(name,emp.ename);
printf("Enter the Employee Id: ");
scanf("%d",&emp.eno);
id=emp.eno;
printf("Enter the Basic Salary: ");
scanf("%f",&emp.bsal);
basic=emp.bsal;
hra=basic*.10;
da=basic*.35;
tds=basic*.15;
gross=basic+hra+da;
net=gross-tds;
printf("SALARY DETAILS FOR THE MONTH\n");
printf("-----------------------------");
printf("\nEmployee Name\t: %s",name);
printf("\nEmployee No.\t: %d",id);
printf("\nBasic salary\t: %.2f",basic);
printf("\nHRA\t\t: %.2f",hra);
printf("\nDA\t\t: %.2f",da);
printf("\nTDS\t\t: %.2f",tds);
printf("\nGross Salary\t: %.2f",gross);
printf("\nNet Salary\t: %.2f",net);
getch();
}
Output:
EMPLOYEE PAYROLL PROCESSING
--------------------------------------------
DETAILS OF THE EMPLOYEE
Enter the Employee Name: Arun
Enter the Employee Id. : 2001
Enter the Basic Salary : 10000
SALARY DETAILS FOR THE MONTH
--------------------------------------------
Employee Name : Arun
Employee Id : 2001
Basic Salary : 10000.00
HRA : 1000.00
DA : 3500.00
TDS : 1500.00
Gross Salary : 14500.00
Net Salary : 13000.00

3. Examine the differences between nested structures and array of structures.(15)


Array of Structures: It is possible to create an array whose elements are of
structure type. Such an array is known as array of structures.
ARRAY OF STRUCTURES

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

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

int main()
{
int i;
struct student record[2];

// 1st student's record


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

// 2nd student's record


record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;

// 3rd student's record


record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;

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


{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}

OUTPUT:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000

Nested structures
A structure can be nested within another structure.

Let's see the code of nested structure.

struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
Accessing Nested Structure

We can access the member of nested structure by


Outer_Structure.Nested_Structure.member as given below:

1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy

#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
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.pin,emp.add.phone);
}

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


A union is a collection of one or more variables, possibly of different types. In union, all
the members of an object share the same memory. The amount of memory allocated to it
is the amount necessary to contain its largest member.but only one member can contain a
value at any given time.
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.

The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in the above example, Data type will occupy 20 bytes of memory
space because this is the maximum space which can be occupied by a character string.

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

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

int 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, "C Programming");


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

return 0;
}
When the above code is compiled and executed, it produces the following result −

data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at
a time.

You might also like