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

Lecture 9 - Custom Data Types v1

The document is a lecture on custom data types in C programming, focusing on structures, unions, and enumerations. It explains the definition, declaration, initialization, and access of structure members, as well as the differences between structures and unions in terms of memory allocation. Additionally, it includes examples and exercises for practical understanding of these concepts.

Uploaded by

siamfaysal27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 9 - Custom Data Types v1

The document is a lecture on custom data types in C programming, focusing on structures, unions, and enumerations. It explains the definition, declaration, initialization, and access of structure members, as well as the differences between structures and unions in terms of memory allocation. Additionally, it includes examples and exercises for practical understanding of these concepts.

Uploaded by

siamfaysal27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

ME 172

Introduction to C Programming Language

Department of Mechanical Engineering, BUET

Lecture-9
Custom Data Type
Courtesy:
Nusrat Jahan Salim
Md. Asaduzzaman Sourov
Md. Moyeenul Hossain Ratul

ME 172 : C Programming Sessional 11/26/2024 1


Topic
CUSTOM DATA TYPES

structure
union
enumeration

ME 172 : C Programming Sessional 11/26/2024 2


STRUCTURES
• Similar to an array but more flexible

• A structure is a user defined data type that groups logically related data items of
different data types into a single unit, for convenient handling.

• A variable of structure type can store multiple data items of different data types
under the one name. As the data of employee in company that is name, Employee
ID, salary, address, phone number is stored in structure data type.

• An array allows you to store similar data types together while a structure is different in the sense
that it allows you to store different data types together.

ME 172 : C Programming Sessional 11/26/2024 3


STRUCTURES DEFINITION
struct tag_name •Keyword struct introduces the structure
definition
{
data_type member1;
• tag_name, names the structure definition
data_type member2;
------ ---------
}; •This statement defines a new data
type called struct ME172.
Example:
struct ME172
{ •Each variable of this data type will
char student_name[50]; consist of a character variable called
int roll; “student_name”, an integer variable
float marks;
called “roll”, a float variable called
Name char grade;
of the }; “marks” and a character variable
type called “grade”.

ME 172 : C Programming Sessional 11/26/2024 4


STRUCTURES DEFINITION
• Variables declared within the braces of the structure definition are the
structure’s members.
• Members of the same structure type must have unique names, but two
different structure types may contain members of the same name
without conflict
• A structure format can be defined outside or within the main function.
Defining a structure format before the main function makes it global
and allowing it to be used by other functions which we will see later on.

* Each structure definition must end with a semicolon


* Do not confuse the tag_name with the structure variable declaration.
* Structure definitions do not reserve any space in memory; each definition creates a new data type used to
define variables.

ME 172 : C Programming Sessional 11/26/2024 5


Declaring Structure Variables
• Once the new structure data type has been defined one or more variables can
be declared to be of that type.

struct ME172 std1,std2,std3;


• Declares and sets aside storage for three variables – std1, std2,
and std3 – each of type struct ME172
struct ME172 std[25];
• Declares a 25-element array of struct ME172; allocates 25
units of storage, each one big enough to hold the data of one
ME172
struct ME172 *std;
• Declares a pointer to an object of type struct ME172

ME 172 : C Programming Sessional 11/26/2024 6


Declaring Structure Variables
• It is also possible to combine the declaration of the structure type and the structure
variables in one statement
For example: is same as... or even...

struct ME172 struct


struct ME172
{ {
{
char std_name[50]; char std_name[50];
char std_name[50];
int roll; int roll;
int roll;
float marks; float marks;
float marks;
char grade; char grade;
char grade;
} std1, std2, std3; } std1, std2, std3;
};

struct ME172 std1, std2, std3;


* The structure tag name is optional.
** If a structure definition does not contain a structure tag name, variables of the structure type must be
declared in the structure definition—not in a separate declaration.

ME 172 : C Programming Sessional 11/26/2024 7


Initializing Structures
• Like primary variables and arrays, structure variables can also be initialized
where they are declared. The format used is quite similar to that used to
initiate arrays.
• For example,
• struct ME172 std1= {“joy", 51 , 75.00, "A"};

* If there are fewer initializers in the list than members in the structure, the
remaining members are automatically initialized to 0 (or NULL if the member
is a pointer).
* Structure variables defined outside a function definition (i.e., externally) are
initialized to 0 or NULL if they are not explicitly initialized in the external
definition.

ME 172 : C Programming Sessional 11/26/2024 8


Accessing Structure Members
• Individual members of a struct variable may be accessed using the structure member operator
(the dot, “.”):
std1.roll ; std1.marks; std1.grade;

• Or , if a pointer to the struct has been declared and initialized


Some_name *myptr = &std1 ;
by using the structure pointer operator (the “->“):
myptr -> roll ;
which could also be written as:
(*myptr).roll ;

• The parentheses are needed here because the structure member operator (.) has a higher precedence than the
pointer dereferencing operator (*).

ME 172 : C Programming Sessional 11/26/2024 9


STRUCTURES
Simple Examples
#include <stdio.h> student.marks = 79;
#include <string.h> student.grade = 'A';

struct ME172 printf(“Student’s name: %s \n”, student.name);


{ printf(“Student’s roll: %d \n”, student.roll);
printf(“Student’s marks: %f \n”, student.marks);
char name[50]; printf(“Student’s grade: %c ”, student.grade);
int roll;
float marks; return 0;
char grade;}; }
int main(void)
{
struct ME172 student;
strcpy(student.name , "Moyeenul");
student.roll = 47;

ME 172 : C Programming Sessional 11/26/2024 10


STRUCTURES
Exercise
• Write a program that will first create a structure format of a grocery shop.
• The structure must contain a product name, the no. of products in the inventory, the
price per unit of that product
• Declare a variable and take the following as input from the keyboard:

Product name: Playstation 4


No. of products: 30
Price per unit: 32000

• Finally print the input values

ME 172 : C Programming Sessional 11/26/2024 11


STRUCTURES
Solution
#include <stdio.h> printf(“\n Enter the price of the product: ”);
struct product scanf(“%f”, &ps4.price);
{
char name[50]; printf(“Product name: %s”, ps4.name);
int num; printf(“\n Product number: %d”, ps4.num);
float price; printf(“\n Product price: %f”, ps4.price);
};
}
void main(void)
{
struct product ps4;

printf(‘’’Enter the name of the product: ”);


gets(ps4.name);
printf(“Enter the number of products: ”);
scanf(“%d”, &ps4.num);

ME 172 : C Programming Sessional 11/26/2024 12


Arrays of Structures
Consider the previous structure variable which was declared:
struct ME172 student;
This is a structure variable for a single student containing the name, roll, marks
and grade of the student.
But, if one was to store the data of 30 students of section F1, 30 structure
variables would have to be declared.
To overcome this problem we can declare an array of structures:
struct ME172 student[30];
The array student[30] will now contain the names, rolls, marks and grades of the
30 students.

ME 172 : C Programming Sessional 11/26/2024 13


Arrays of Structures
#include <stdio.h> for (i=0; i<3; i++)
{
struct product
printf(" Product: %s", food[i].name);
{ printf("\n Product number: %d", food[i].num);
printf("\n Product price: %f", food[i].price);
char name[50];
printf("\n\n\n");
int num; }
}
float price;
};
void main(void)
{
struct product food[3] =
{{"Burgers", 101, 70},
{"Khichuri", 1003, 250},
{"Shutki Vorta", 105, 30}};
int i;

ME 172 : C Programming Sessional 11/26/2024 14


CLASS PERFORMANCE !!!
• Write a C program to manage a small collection of car records. Create a
structure called Car with the following fields:
model (string of up to 50 characters)
manufacturing year (integer)
price (float)
Use a for loop to take the input details for 4 cars,
and then use a while loop to print the details of
the 2nd and 4th cars.

ME 172 : C Programming Sessional 11/26/2024 15


Solution
#include <stdio.h>
struct Car { int i = 0;
char model[50]; while (i < 6) {
int manufacturing_year; if (i == 1 || i == 3) {
float price;
printf("Car %d Details:\n", i
}; + 1);
int main() { printf("Model: %s",
struct Car cars[6]; cars[i].model); // No need to use
\n since fgets includes it
for (int i = 0; i < 4; i++) {
printf("Manufacturing Year:
printf("Enter details for car %d:\n", i + 1); %d\n",
printf("Model: "); cars[i].manufacturing_year);
fgets(cars[i].model, 50, stdin); printf("Price: %.2f\n\n",
printf("Manufacturing Year: ");
cars[i].price);
scanf("%d", &cars[i].manufacturing_year); }
printf("Price: "); i++;
scanf("%f", &cars[i].price); }
getchar();
printf("\n"); return 0;
}
}

ME 172 : C Programming Sessional 11/26/2024 16


Arrays within Structures
• Consider the structure format:
struct ME171
{
char student_name[50];
int roll;
float ct_marks[3];
};
Say, in the main we have declared struct ME171 student[10];

We have seen how individual characters of the structure can be accessed.


Now, if we were to access the 2nd ct mark of the 7th student, we would have to
write:
printf(“%f ”, student[6].ct_marks[1]);

ME 172 : C Programming Sessional 11/26/2024 17


Structures within Structures(Nested Structure)
One structure can be nested within another structure. Using this
facility complex data types can be created.
The structure of Employee can be declared as
struct employee
{ int emp_id; The data member of structure within
char name[20]; structure is accessed by using dot (.)
float salary; symbol twice
int dept_no;
struct date For example:
{ int day; e[0].joining.day;
int month; e[0].joining.month;
int year; e[0].joining.year;
} joining;
} e[50];
ME 172 : C Programming Sessional 11/26/2024 18
Pointers to Structures
The way we can have a pointer pointing to an int, or a pointer pointing to a char,
similarly we can have a pointer pointing to a struct. Such pointers are known as
‘structure pointers’.

main( )
{ We can’t use ptr.name or ptr.callno because ptr
struct book is not a structure variable but a pointer to a
{ structure
char name[25] ;
char author[25] ;
int callno ;
};
struct book b1 = { "Let us C", "YPK", 101 } ;
struct book *ptr ; an arrow operator(->) must be used to refer to
ptr = &b1 ; the structure elements in case of ‘structure
printf ( "\n%s %s %d", b1.name, b1.author, b1.callno ) ; pointers’
printf ( "\n%s %s %d", ptr->name, ptr->author, ptr->callno ) ;
}

ME 172 : C Programming Sessional 11/26/2024 19


Structure to Function
Like an ordinary variable, a structure variable can also be passed to a function. Structures may be passed
to functions by passing individual structure members, by passing an entire structure or by passing a
pointer to a structure
main( ) struct book
{ {
struct book char name[25] ;
{ char author[25] ;
char name[25] ; int callno ;
char author[25] ; };
int callno ; main( )
}; {
struct book b1 = {" C programming ", " ABC ", struct book b1 = { " C programming ", " ABC ", 101 } ;
101 } ; display ( b1 ) ;
display ( b1.name, b1.author, b1.callno ) ; }
}
display ( char *s, char *t, int n ) display ( struct book b )
{ {
printf ( "\n%s %s %d", s, t, n ) ; printf ( "\n%s %s %d", b.name, b.author, b.callno ) ;
} }

ME 172 : C Programming Sessional 11/26/2024 20


UNION
• Another custom data type
• Very much similar to structure

struct ME union me
{ {
char student_name[6]; char student_name[6];
int roll; int roll;
float marks; float marks;
char grade; char grade;
}student_1; }student_2;

ME 172 : C Programming Sessional 11/26/2024 21


Structure vs. Union
Memory Allocation: Structure

. .. .. . … … . . .. .. . .

grade roll student_name[6] marks


takes 1 byte takes 4 bytes takes 7 bytes takes 8 bytes

Total memory consumption 20 bytes


Memory Allocation: Union

. . . .. .. .

grade takes 1 byte

roll takes 2 bytes


student_name[6] takes 7 bytes

marks takes 8 bytes 22

ME 172 : C Programming Sessional Total


ME 172 :memory
C Programming consumption only 8 bytes
Sessional
11/26/2024 22
Structure vs. Union
#include <stdio.h>
void main() {
struct ME
{
char student_name[6];
int roll;
float marks;
char grade;
}student_1; Try yourself
union me
{
char student_name[6];
int roll;
float marks;
char grade;
}student_2;

printf("size of struc_student_1: %d\n",sizeof(student_1));


printf("size of union_student_2: %d\n",sizeof(student_2));
}

ME 172 : C Programming Sessional 11/26/2024 23


Limitation of Union
void main(){
struct ME
{
char student_name[6];
int roll;
float marks;
char grade;
}student_1;
union me
{
char student_name[6];
int roll;
float marks;
char grade;
}student_2;
student_1.roll=910061;
student_2.roll=910061;
student_1.marks=95;
student_2.marks=95;
printf("st1 roll: %d st1 marks: %.1f\n", student_1.roll, student_1.marks);
printf("st2 roll: %d st2 marks: %.1f\n", student_2.roll, student_2.marks);
}

ME 172 : C Programming Sessional 11/26/2024 24


ENUMERATION
• Another custom data type like structure or union
• Main differences are in members type and variable assigning
Format:
enum product{ • Comma(,) should be used instead of semicolon(;)
shampoo, • All members are assigned as integer type data
soap, toothpaste, toothbrash
}; No comma(,) after the last member

enum product washroom; washroom is a variable which takes its value as shampoo
washroom= shampoo;

shampoo is a char type array(string).


How can it be an integer type data???

ME 172 : C Programming Sessional 11/26/2024 25


ENUMERATION
void main()
{
enum product{
shampoo, soap, toothpaste, toothbrash
};
printf("shampoo:%d\nsoap:%d\ntoothpaste:%d\ntoothbrash:%d\n\n", shampoo, soap, toothpaste, toothbrash);
}

void main()
{
enum product{
shampoo, soap, toothpaste=134, toothbrash
};
enum product washroom;
washroom= shampoo;
printf("shampoo:%d,soap:%d,toothpaste:%d,toothbrash:%d", shampoo, soap, toothpaste, toothbrash);
}

ME 172 : C Programming Sessional 11/26/2024 26


Structure vs. Union vs. Enumeration
Feature Structure Union Enumeration
Definition A user-defined data type to A user-defined data type where all A user-defined data type to assign
group variables of different members share the same memory names to integral constants.
types. location.

Memory Allocates separate memory for Allocates a shared memory space for No memory is allocated; it uses
Allocation each member. the largest member. constants.

Size Sum of sizes of all members. Size is equal to the size of the No memory size as it only assigns
largest member. names to integers.
Access All members can be accessed Only one member can be accessed Each enumeration value
simultaneously. at a time (due to shared memory). represents a unique constant.

Use Case Used to store and manipulate Used to save memory when only Used to improve code readability
multiple related variables of one value is needed at a time. and manage constant values.
different types.

Example struct Person { int age; char union Data { int i; float f; }; enum Days { MON, TUE, WED
name[50]; }; };

ME 172 : C Programming Sessional 11/26/2024 27


Assignment
• Write a C program to manage a small collection of items in a store. Create a structure called
Item with the following fields:
 Item Name (string of up to 50 characters)
 Item ID (integer)
 category (string to indicate the item’s category, like "Electronics", "Clothing", etc.)
• Inside the structure, use a union to store:
 The warranty period (as an integer, applicable only for items in the "Electronics" category).
 The size (as a string, applicable only for items in the "Clothing" category).
• The program should:
 Take input for 5 items.
 Based on the category, input either the warranty period (for Electronics) or the size (for Clothing).
 Print the details of each item.

ME 172 : C Programming Sessional 11/26/2024 28


Thank you

The only true wisdom is in knowing “ you know nothing”.

- Socrates

ME 172 : C Programming Sessional 11/26/2024 29

You might also like