0% found this document useful (0 votes)
6 views25 pages

C Programming: Structures and Unions Guide

Pop using c notes m1-m5

Uploaded by

nandankp332
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)
6 views25 pages

C Programming: Structures and Unions Guide

Pop using c notes m1-m5

Uploaded by

nandankp332
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

Principles of Programming using C BPOPS103

Principles of Programming using C BPOPS103

Module 5 –Part 1
Structure, Union, and Enumerated Data Type: Introduction, structures and functions,Unions,
unions inside structures, Enumerated data type.

Files: Introduction to files, using files in C, reading and writing data files. , Detecting end of file

STRUCTURES
Introduction

Structure stores related information about an entity. Structure is basically a user-defined data
type that can store related information together. The major difference between a structure and an
array is that an array can store only information of same data type.

Q)What is structure? Explain the C syntax of structure declaration and initialization with
example.(Dec.2015/Jan.2016,Dec.2014/Jan.2015,June2016,Dec.2016/Jan.2017,June2018)

Definition: Structure is a collection of elements of same or different data types under a single
name.
Structure Declaration: A structure is declared using the keyword struct followed by the
structure name. All the variables or members of the structure are declared within the structure.

Syntax for Defining Structure: Example:


struct structure_name struct employee
{ {
datatype member1; char name[20];
datatype member2; float salary;
------------ int empno;
------------ };
datatype member n;
};

Now the structure has become a user-defined data type. Here,

• structure_name is used to identify the structure later in the program.


• Each data type can be any data type in C.
• The item member 1, member 2,-----member n are the members of the structure.

CSE Dept,VCET, Puttur. Page 1


Principles of Programming using C BPOPS103

Declaring Structure Variables: The structure declaration, does not allocate any memory.
Memory is allocated for the structure when we declare a variable of the structure. The syntax of
declaring structure variables is shown below:

Method 1: Example:
struct structure_name struct employee
{ {
datatype member 1; char name[20];
datatype member 2; float salary;
------------ int empno;
------------ };
datatype member n; struct employee emp1, emp2;
};
struct structure_name variable1, variable2,….;

Method 2: Example:
struct structure_name struct employee
{ {
datatype member 1; char name[20];
datatype member 2; float salary;
------------ int empno;
------------ }emp1, emp2;
datatype member n;
}variable1, variable2,….;
Here emp1, emp2 are the types of employee where emp1 has members name, salary, and empno
consume 20+4+2 bytes that means 26 bytes. Similarly, emp2 consumes 26bytes.
Structure Initialization:
The general syntax:
Method 1: Method 2:
struct structure_name struct structure_name
{ {
datatype member 1; datatype member 1;
datatype member 2; datatype member 2;
------------ ------------
------------ ------------
datatype member n; datatype member n;
} variable = { value1, value2,…valuen,...}; };
struct structure_name variable = { value1,
value2,…valuen,...};

CSE Dept,VCET, Puttur. Page 2


Principles of Programming using C BPOPS103

Example1:
struct employee
{
char name[20];
float salary;
int empno;
};
struct employee emp1={“Raj”,1000,1};
Example2:
struct employee
{
char name[20];
float salary;
int empno;
} emp1={“Raj”,1000,1};
Define structure. Explain how structure members are accessed using dot operator. [July
2017]
Accessing members of structures (Usingthe Dot (.) Operator):
The member of structure is accessed using the dot operator(.).
Syntax:
struct_variable.membername;
E.g.: [Link]

Example: Consider the structure definition and initialization as shown below:


struct employee
{
char name[10];
float salary ;
int empno;
};
struct employee e = {“Raj”,10000,1};

CSE Dept,VCET, Puttur. Page 3


Principles of Programming using C BPOPS103

The members of structure variable e can be accessed using dot operator as illustrated below:
[Link] can access the string “Raj”
[Link] can access the value 10000
[Link] can access the value of 1
Ex 1: Write a program to read structure employee number, name, salary and print the
details.
#include<stdio.h>
struct employee
{
char name[20];
float salary;
int empno;
};
void main()
{
struct employee e;
printf("Enter name, salary and number of employee\n");
scanf("%s%f%d",[Link],&[Link] ,&[Link]);
printf("Entered name salary and number of employee is\n");
printf("%s %f %d",[Link], [Link],[Link]);
}
Output:
Enter name, salary and number of employee
Raj 50000 1
Entered name salary and number of employee is
Raj 50000.000000 1

Ex 2: Write C program to add two complex numbers using structures.


#include <stdio.h>
int main()
{
struct complex
{
int real;
int imag;
};
void main()

CSE Dept,VCET, Puttur. Page 4


Principles of Programming using C BPOPS103

struct complex c1, c2, sum;


printf("Enter real and imaginary part of first complex number:\n");
scanf("%d%d",&[Link],&[Link]);
printf("Enter real and imaginary part of second complex number:\n");
scanf("%d%d",&[Link],&[Link]);
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
printf("Sum=%d+%di",[Link], [Link]);
}
******************************
COPYING AND COMPARING STRUCTURES
Two variables of the same structure type can be copied the same way as ordinary variables.
Syntax:
structstructure_name
{
datatype member1;
datatype member2;
.
.
.
datatype member;
};
struct structurename variable1, variable2= {list of elements};
variable1=variable2;

E.g.:
struct student
{
int roll_no;
char name[30];
float marks;
};
struct student s1, s2 = {123, “John”,92};
s1=s2;

CSE Dept,VCET, Puttur. Page 5


Principles of Programming using C BPOPS103

C does not permit comparison of one structure variable with another. However, individual
members of one structure can be compared with individual members of another structure.
For example, to compare the marks of two students, we will write
if(s1. marks > s2. marks)
***************************
Write a note with example on i) array within structure ii) arrays of structure iii)structure
within structure.[Dec 2018]

ARRAY WITHIN (INSIDE) STRUCTURE


Array within(inside) Structure means there is an array inside structure.
E.g.:
#include<stdio.h>
struct student
{
char name[20];
int usn;
int marks[3];//array within the structure
};
void main()
{
struct student s;
int i,n,total=0;
printf("Enter the usn and name\n");
scanf("%d%s",&[Link],[Link]);
printf("Enter marks in 3 subjects\n");
for(i=0;i<3;i++)
{
scanf("%d",&[Link][i]);
total = total + [Link][i];
}
printf("Student with usn %d and name %s has total marks=%d\n",[Link],[Link],total);
}
Output
Enter the usn and name
101
Raj
Enter marks in 3 subjects
50 60 70
Student with usn 101 and name Raj has total marks=180

CSE Dept,VCET, Puttur. Page 6


Principles of Programming using C BPOPS103

Explain the concept of array of structures, with a suitable C program. ( Dec.2014/Jan.2015)


ARRAY OF STRUCTURES
Syntax:
struct structurename
{
datatype member1;
datatype member2;
.
.
.
datatype member;
};
struct structurenamearray[size];

Eg 1: Eg 2:
struct student struct student
{ {
int roll_no; int roll_no;
char name[30]; char name[30];
float marks; float marks;
}; }s[100];
struct student s[100];

Accessing members of array of structure:


structure_variable[subscript].members;
to access first student
s[0].roll_no
s[0].name
s[0].marks
to access last student
s[99].roll_no
s[99].name
s[99].marks

Write a C program to read name, USN, and marks of n students and display the sum and
average of the marks using structure.(July 2021)
#include <stdio.h>
struct student
{
int usn, marks;
char name[20];

CSE Dept,VCET, Puttur. Page 7


Principles of Programming using C BPOPS103

}s[20];
void main()
{
int i, n;
float total = 0, avg;
printf("Enter the number of students\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the USN:");
scanf("%d", &s[i].usn);
printf("Enter the student name:");
scanf("%s", s[i].name);
printf("Enter the marks:");
scanf("%d", &s[i].marks);
total = total + s[i].marks;
}
avg = total / n;
printf(“the sum is %f \t the total is %f”,total,avg);
}

Output:
Enter the number of students
2
Enter the USN:11
Enter the student name:aaa
Enter the marks:80
Enter the USN:12
Enter the student name:bbb
Enter the marks:90
the sum is 170.000000 the average is 85.000000

Write a C program to read name, USN, and marks of n student using structure. Also
search marks of a student based on name. (Jan 20)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

CSE Dept,VCET, Puttur. Page 8


Principles of Programming using C BPOPS103

struct student
{
int usn, marks;
char name[20];
};
void main()
{
int i,n;
char sname[30]; //student name is to be searched
struct student s[100];
printf("Enter the number of the students\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the USN:");
scanf("%d",&s[i].usn);
printf("Enter the name of student:");
scanf("%s",s[i].name);
printf("Enter the marks:");
scanf("%d",&s[i].marks);
}
printf("Enter a name of a student to be searched\n");
scanf("%s",sname);
for(i=0;i<n;i++)
{
if(strcmp(sname, s[i].name)==0)
{
printf("%s scored %d marks",sname,s[i].marks);
exit(0);
}
}
printf("Student is not found");
}

Output:
Enter the number of the students
2
Enter the USN:11
Enter the name of student:Veena
Enter the marks:87
Enter the USN:12
Enter the name of student:Suhas

CSE Dept,VCET, Puttur. Page 9


Principles of Programming using C BPOPS103

Enter the marks:90


Enter a name of a student to be searched
Suhas
Suhas scored 90 marks

Implement structures to read, write and compute average- marks of the students, list the students
scoring above and below the average marks for a class of N students.(Jan 19)(lab program)
#include <stdio.h>
struct student
{
int usn, marks;
char name[20];
}s[20];
void main()
{
int i, n;
float total = 0, avg;
printf("Enter the number of student\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the USN:");
scanf("%d", &s[i].usn);
printf("Enter the student name without white spaces:");
scanf("%s", s[i].name);
printf("Enter the marks:");
scanf("%d", &s[i].marks);
total = total + s[i].marks;
}
avg = total / n;
printf("Students scored above the average marks\nUSN\tNAME\tMARKS\n");
for (i = 0; i < n; i++)
{
if (s[i].marks >= avg)
{
printf("%d\t%s\t%d\n", s[i].usn, s[i].name, s[i].marks);
}
}
printf("Students scored below the average marks\nUSN\tNAME\tMARKS\n");
for (i = 0; i < n; i++)
{
if (s[i].marks < avg)
{
printf("%d\t%s\t%d\n", s[i].usn, s[i].name, s[i].marks);
}
}
}

CSE Dept,VCET, Puttur. Page 10


Principles of Programming using C BPOPS103

Explain structures within a structure with an example. (June 2016,July 2021)


STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES):
• A structure inside another structure is called a nested structure. A structure is a member
of another structure.

Syntax:

struct structure_name1
{
datatype member1;
.
.
datatype member;
};

struct structure_name2
{
datatype member1;
.
.
struct structure_name1 variable;
};

Consider the following example program.


#include<stdio.h>
struct date
{
int d;
int m;
int y;
};
struct employee
{
char name[20];
float salary;
int empno;
struct date doj;
};

void main()
{
struct employee e;
[Link].d= 10;

CSE Dept,VCET, Puttur. Page 11


Principles of Programming using C BPOPS103

[Link].m=1;
[Link].y=2020;
printf(“Date of Joining of employee is %d\n”,[Link].d);
printf(“Month of Joining of employee is %d\n”,[Link].m);
printf(“Year of joining of employee is %d\n”, [Link].y);
}
Output:
Date of Joining of employee is 10
Month of Joining of employee is 1
Year of Joining of employee is 2020
*****************************************
STRUCTURES AND FUNCTIONS
There are three types of parameter passing in functions based on structures.
1. Passing individual members of a structure to function
2. Passing entire structure to a function
3. Passing structure as a pointer to a function

1) Passing individual members of a structure to function:


Ex: Program to add two integers using structure and function

#include <stdio.h>
struct addition
{
int a,b;
};
void add(int a, int b)
{
int c;
c=a+b;
printf(“sum=%d”,c);
}
void main()
{
struct addition p;
printf(“enter two integers\n”);
scanf(%d%d”,&p.a,&p.b);
add(p.a,p.b);
}
In this program a and b are two members of structure addition they are accessed in function main
and passed to add() for addition purpose.

2)Passing entire structure to a function:

CSE Dept,VCET, Puttur. Page 12


Principles of Programming using C BPOPS103

Q) Write a C program that accepts a structure variable as a parameter to a function from


a function call. (June 2019)

Ex: Program to add two integers using structure and function


#include <stdio.h>
struct addition
{
int a,b;
}
void add(struct addition p)
{
int c;
c=p.a+p.b;
printf(“sum=%d”,c);
}
void main()
{
struct addition p;
printf(“enter two integers\n”);
scanf(“%d%d”,&p.a,&p.b);
add(p);
}
In this program the function call has structure as a parameter. Since the function is working on a
copy of the structure, any changes to structure members within the function are not reflected in
the original structure (in the calling function).
3)Passing structure as a pointer to a function:
This approach employs a concept called pointers to pass the structure as an argument. To access
the members of a structure using pointer ‘pointing-to’ operator(->) is used. In this case, the
address of the structure is passed to the called function. The function can access indirectly the
entire structure and work on it.
Ex: Program to add two integers using structure and function
#include <stdio.h>
struct addition
{
int a,b;
};
void add(struct addition *ptr)
{
int c;

CSE Dept,VCET, Puttur. Page 13


Principles of Programming using C BPOPS103

c=ptr->a + ptr ->b;


printf(“sum=%d”,c);
}
void main()
{
struct addition x,*p;
p= &x;
printf(“enter two integers\n”);
scanf(“%d%d”, &p->a, &p ->b);
add(p);
}
In above program x is a pointer used to access members of addition structure a and b
respectively. In function call address of members, a and b are passed to the function definition to
process sum.
*********************************
Explain typedef with example [Jan 2018]
TYPE DEFINITION (typedef):
The typedef is a keyword using which the programmer can create a new data type name for an
already existing data type name.
Syntax:
typedef < existing_name> <new_name>;

In the above syntax, 'existing_name' is the name of an already existing variable while
‘new_name’ is another name given to the existing variable.
E.g.: int a, b;
Above statement is possible to write like below,
typedef int unit;
unit a, b;
In above example unit is alternate name for int, where unit is of type integer.

CSE Dept,VCET, Puttur. Page 14


Principles of Programming using C BPOPS103

typedef in structure:
Syntax:
typedef struct structure_name
{
datatype member1;
.
.
datatype membern;
} new_structurename;
new_structurename variable1, variable2,…;
• The typedef is keyword used in front of struct keyword.
• While declaring the variables for structure keyword struct is not used

E.g.:
typedef struct student
{
char name[20];
int age;
}stud;
stud s1,s2;

Example program:
#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
void main()
{
stud s1;
printf("Enter the details of student: ");
printf("\nEnter the name and age of student:");
scanf("%s%d",[Link],&[Link]);
printf("\n Name of the student is : %s", [Link]);
printf("\n Age of the student is : %d", [Link]);
}

CSE Dept,VCET, Puttur. Page 15


Principles of Programming using C BPOPS103

Output
Enter the details of student:
Enter the name and age of student: Anil 30
Name of the student is : Anil
Age of the student is : 30

Q) Write a C program to compare two student structures with data members name and
marks and print if students are same or different. (June 2018)
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int marks;
};
void main()
{
struct student s1={"Raj",90};
struct student s2={"Raj",90};
int result;
result=strcmp([Link],[Link]);
if(result==0 && [Link]==[Link])
printf("Students are same");
else
printf("Students are different");
}
Output:
Students are same

CSE Dept,VCET, Puttur. Page 16


Principles of Programming using C BPOPS103

Q)Differentiate between structure and array. Explain the syntax of structure declaration in
C with example.(Jan 2021)
DIFFERENCE BETWEEN ARRAYS AND STRUCTURE
Arrays Structures
An array is a collection of elements of the
Structure is a collection of elements of
same data type. different data type.
An array is a derived data type. A structure is a user defined data type.
Array uses index/subscript for accessingStructures uses (.) operator for accessing
elements of the array. the member of a structure.
Array name points to the first element in that
Structure name does not point to the first
array so, array name is a pointer. element in that structure so, structure
name is not a pointer.
To access an element requires less time To access a member requires more time
compared with structure. compared with an array
Syntax: Syntax:
type array_name[size]; struct sruct_name{
type element1;
type element1;
.
.
} variable1, variable2, . .;
Eg: int a[10]; Eg: struct employee
{
char name[20];
int empno;
float salary;
};

UNION
• Union is an user defined data type.
• Similar to structures, It is a collection of related variables of same or different data types.
• There is distinction between structure and union. In structures, each member has its own
storage location, where as all the members of a union use the same location, the fields of
a union will share memory. Union can handle only one member at a time.
• Unions are used to save memory. They are useful for applications that involve multiple
members and values of all members not needed at same time.
Declaring a Union:

Syntax:

CSE Dept,VCET, Puttur. Page 17


Principles of Programming using C BPOPS103

union name
{ Example:
datatype member 1; union student
datatype member 2; {
: int rollno;
datatype member n char name[30];
}; float marks;
};
DECLARING UNION VARIABLE

union name
Example:
{
union student
datatype member 1;
{
datatype member 2;
int rollno;
:
char name[10];
datatype member n;
float marks;
} variable1, variable2,…;
} s1 ;

In the above example, name member requires 10 bytes, compiler allocates 10 bytes for union
variable s1 and figure shows how all members share same memory.

Accessing a Member of a Union


To access the fields of a union, use the dot operator (.), i.e.,the union variable name followed by
the dot operator followed by the member name.

Initializing Unions
The difference between a structure and a union is that in case of a union, the fields share the
same memory space, so new data replaces any existing data. The fields of a union cannot be
initialized all at once.
Example program:

#include <stdio.h>
union POINT
{
int x;
int y;
}p;
void main()
{

CSE Dept,VCET, Puttur. Page 18


Principles of Programming using C BPOPS103

p.x = 4;
p.y = 5;
printf("\n The coordinates of p are %d and %d", p.x, p.y);
}

Output
The coordinates of P are 5 and 5
Programming Tip
UNIONS INSIDE STRUCTURES
Unions can be very useful when declared inside a structure. Consider an example in which we
want a field of a structure to contain a string or an integer, depending on what the user specifies.
The following code illustrates such a scenario:

#include <stdio.h>
struct student
{
union
{
char name[20];
int roll_no;
};
int marks;
};
int main()
{
struct student stud;
char ch;
printf("\n Do you want to enter the name? (Y or N): ");
scanf(“%c”,&ch);
if(ch= =‘Y’)
{
printf("\n Enter the name: ");
gets([Link]);
}
else
{
printf("\n Enter the roll number: ");
scanf("%d", &stud.roll_no);
}
printf("\n Enter the marks: ");
scanf("%d", &[Link]);
}
Q) What is union? How to declare Union? List out the differences and similarities between
Structure and Union. (Feb 2022)

Similarities between Structure and Union.

CSE Dept,VCET, Puttur. Page 19


Principles of Programming using C BPOPS103

1. Both are user-defined data types used to store data of same or different types as a single unit.
2. Their members can be of any type, including other structures and unions or arrays.
3. Both structures and unions support only assignment = operator. 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.
5. ‘.’ operator is used for accessing members.

Differences and similarities between Structure and Union.

Structure Union
struct keyword to define a structure. union keyword to define a union.
Every member within structure is assigned a In union, a memory location is shared by all
unique memory location. the data members.
The total size of the structure is the sum of the
The total size of the union is the size of the
size of every data member. largest data member.
It is mainly used for storing various data types.
It is mainly used for storing one of the many
data types that are available.
We can retrieve any member at a time. We can access one member at a time in the
union.
Changing the value of one data member will Changing the value of one data member will
not affect other data members in structure. change the value of other data members in
union.

***************************
ENUMERATED DATA TYPE

Enumerated data type: It is a user-defined data type.


Syntax of creating it is :

enum enumeration_name{ identifier 1, identifier 2, .. identifier n};


Here ,
• enum is keyword
• enumeration_name is user-defined enumerated data type
• identifier 1, identifier 2, .. identifier n are enumeration constants.

The compiler automatically assigns integer digits beginning with 0 to all the enumeration
constants. That is, the enumeration constant identifier1 is assigned 0, identifier2 is assigned 1,
and so on.

Example:
enum day {Mon, Tues, Wed};
Here, enum day is enumerated data type and it is the name given to set enumeration constants
Mon, Tues, Wed with the values,
Mon=0, Tues=1, Wed=2

CSE Dept,VCET, Puttur. Page 20


Principles of Programming using C BPOPS103

This automatic assignments can be overridden by assigning values explicitly to the enumeration
constants.
For example
enum day {Mon = 1, Tues, Wed};
Here,
Mon=1, Tues=2, Wed=3.
Constant Mon is assigned with 1 and remaining constants are assigned values that increase
successively by 1.

Enumerated Variables and Assigning Values to Enumerated Variables:


Syntax of declaring Enumerated Variables is:

enum enumeration_name { identifier1 , identifier2, .. identifier n }v1,v2,…,vn;


or
enum enumeration_name { identifier1, identifier2, .. identifier n};
enum enumeration_name v1,v2,…,vn;

The enumerated variables v1, v2, .. vn can only have one of the values identifier 1, identifier 2, ..
identifier n.

The following assignments are valid:


v1 = identifier3;
v5 = identifier1;
Example:
enum day {Mon, Tues, Wed}d1,d2;
d1= Mon;
d2= Tues;
Example program:
#include <stdio.h>
void main()
{
enum colour{ Red,Blue,Green };
enum colour c;
printf(“%d”,Red);
c= Red;
printf(“%d\t”,c);
c= Blue;
printf(“%d”,c);
}

Comparing enum variables:


C allows to compare enum variables.
Ex: enum day {Mon, Tues, Wed}d1,d2;
d1= Mon;
if ( d1==Mon)
d2=Wed;

CSE Dept,VCET, Puttur. Page 21


Principles of Programming using C BPOPS103

Enumeration Type Conversion:


We can type cast, an integer to an enumerated type.
Ex:
enum day {Mon, Tues, Wed};
enum day d1;
d= Mon; //valid in C
d = 2; // illegal in C
d = (enum day) 2; // valid in C
*********************************
VTU Questions

1. What is structure? Explain the C syntax of structure declaration and initialization with
example.(Jan.2016,Dec.2014/Jan.2015,June2016,Dec.2016/Jan.2017,June2018)
2. Write a C program that accepts a structure variable as a parameter to a function from a
function call.( June 2019)
3. Define structure. Explain how structure members are accessed using dot operator. [July
2017,July 2021]
4. Write a note with example on i) array within structure ii) arrays of structure iii)structure
within structure.[Dec 2018,Jan 2021]
5. Explain the concept of array of structures, with a suitable C program.(
Dec.2014/Jan.2015)
6. Write a C program to read name, USN, and marks of n students and display the sum and
average of the marks using structure.(July 2021)
7. Write a C program to read name, USN, and marks of n student using structure. Also
search marks of a student based on name. (Jan 20)
8. Implement structures to read, write and compute average- marks of the students, list the
students scoring above and below the average marks for a class of N students.(Jan 19)(lab
program)
9. Implement structure to read and display Book_title, Book_author, and Book_id for N
books.(Jan 2021)
10. Explain structures within a structure with an example. (June 2016,Jan 2020,July 2021)
11. write a C program that accepts a structure variable as a parameter to a function from a
function call.( June 2019)
12. Explain typedef with example [Jan 2018]
13. Write a C program to compare two student structures with data members name and marks
and print if students are same or different. (June 2018)
14. Write a C program to maintain record of n students using structures with 4 fields
(Rollno,marks,name and grade). Print the names of students with marks >=70.(Aug 2020)

CSE Dept,VCET, Puttur. Page 22


Principles of Programming using C BPOPS103

#include <stdio.h>
union ss
{
char name[20];
int roll_no;
};
struct student
{
union ss s;
int marks;
};
int main()
{
struct student stud;
char ch;
printf("\n Do you want to enter the name? (Y or N): ");
scanf(“%c”,&ch);
if(ch=='Y')
{
printf("\n Enter the name: ");
//gets([Link]);
//gets([Link]);
scanf("%s",[Link]);
}
else
{
printf("\n Enter the roll number: ");
scanf("%d", &stud.s.roll_no);
}
printf("\n Enter the marks: ");
scanf("%d", &[Link]);

CSE Dept,VCET, Puttur. Page 23


Principles of Programming using C BPOPS103

printf("\n the name:%s ",[Link]);


printf("\n the marks:%d ",[Link]);
}
Do you want to enter the name? (Y or N): Y
Enter the name: SSS
Enter the marks: 45
the name:SSS
the marks:45
**********************
#include <stdio.h>
struct student
{
union
{
char name[20];
int roll_no;
};
int marks;
};
int main()
{
struct student stud;
char ch;
printf("\n Do you want to enter the name? (Y or N): ");
scanf(“%c”,&ch);
if(ch=='Y')
{
printf("\n Enter the name: ");
gets([Link]);
}
else

CSE Dept,VCET, Puttur. Page 24


Principles of Programming using C BPOPS103

{
printf("\n Enter the roll number: ");
scanf("%d", &stud.roll_no);
}
printf("\n Enter the marks: ");
scanf("%d", &[Link]);
printf("\n the name:%s ",[Link]);
printf("\n the marks:%d ",[Link]);
}
Do you want to enter the name? (Y or N): YKKK
Enter the name:
Enter the marks: 78
the name:KKK
the marks:78

CSE Dept,VCET, Puttur. Page 25

Common questions

Powered by AI

Structures in C are advantageous over arrays when handling different data types together under one unit. Arrays only allow elements of the same data type while structures can contain items of different types which provides greater flexibility when managing data . Additionally, structures help model real-world entities more effectively by grouping related information, like a student's name (string), age (int), and marks (float) under a single entity. This contrasts with arrays which provide less semantic meaning as they only manage homogenous elements .

In C, the primary difference between a union and a structure lies in how memory is allocated and accessed for their members. In a structure, memory is allocated separately for each member, meaning the total size of a structure is the sum of the sizes of its members. In contrast, a union uses shared memory for all its members, allocating enough memory to hold the largest member only, which means that all members occupy the same space . Accessing a member in a structure is done using the dot operator (.), where you access each member separately based on its dedicated memory space. For unions, since all members share the same space, writing to one member overwrites the previous value, which is a critical difference .

In C, structure variables can be passed to functions by value or by reference. When passed by value, a copy of the structure is made for the function to work with, which preserves the original data but can incur overhead. Passing by reference involves using pointers, allowing the function to modify the original structure data, which is more efficient for large structures. This capability is useful because it allows functions to process and manage complex data structures, encapsulating related data and logic within function calls, enhancing code organization and reusability .

The fundamental difference between unions and structures in C regarding memory is that unions share the same memory location for all members, while structures allocate distinct memory for each member. This means a union's size is determined by its largest member, leading to potential memory savings, whereas a structure's size is the sum of all its members' sizes. This influences programming decisions by providing unions as a tool for memory optimization in scenarios where only one member variable is needed at a time, like handling various types of sensor data in embedded systems, while structures are preferred when all members need distinct memory spaces, such as holding multiple attributes simultaneously .

The dot operator is used in C programming to access members of a structure. When you have a structure variable, you can access each member by using this operator. For example, if you have a structure defined as `struct employee { char name[20]; float salary; int empno; };` and a variable of this structure `struct employee emp1;`, you can access its members as `emp1.name`, `emp1.salary`, and `emp1.empno` .

An array of structures in C allows you to store multiple records of the same data structure. This is useful when you need to manage collections of similar entities. Syntax-wise, it is declared as `struct structurename arrayname[size];` For example, if you define a structure for a student with attributes like roll number, name, and marks, you can have `struct student s[100];` to manage 100 student records . Accessing members within an array of structures involves using an index and dot operator, like `s[0].roll_no` to access the roll number of the first student .

Enumerated data types in C enhance both type safety and code readability by allowing the programmer to define a set of named integral constants. This translates into code that is easier to read and less prone to errors since the variable can only hold one of the predefined values, reducing incorrect assignments. For example, defining an enumerated type `enum days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};` results in better readability and makes the codes self-documenting compared to using numbers directly. They ensure that only valid values are assigned, which helps prevent logical errors in the program .

Unions inside structures provide a powerful way to handle data that vary in type or interpretation without allocating separate memory spaces for each variation. For example, consider a scenario where a record should store either a string name or an integer roll number. A union inside a structure can accommodate this flexibility efficiently. For example, `struct student { union { char name[20]; int roll_no; }; int marks; };` Here, the union allows either `name` or `roll_no` to be stored, conserving memory since both cannot be needed simultaneously. This is particularly useful in situations where different data types might be used based on context or input .

Initializing a structure variable in C involves assigning initial values to its members when the variable is declared. This can be done by enclosing the values in curly braces following the variable name. For instance, with a structure `struct employee { char name[20]; float salary; int empno; };`, you can initialize an employee as `struct employee emp1 = {"Raj", 1000.0, 1};` This assigns the name "Raj", salary 1000.0, and employee number 1 to the structure variable `emp1` .

In C programming, file operations using structures involve reading from or writing to files where structured data is stored. This allows programs to persist complex data beyond their runtime, making structures ideal for organizing records that mirror real-world entities, which are then serialized into files. Functions like `fwrite()` and `fread()` can be used to handle entire structures as single entities when interacting with files, providing efficient data manipulation. This capability is crucial for applications that require long-term data storage and retrieval, like databases or configuration file maintenance .

You might also like