You are on page 1of 35

Course Title: Applied Computer

Programming II
Course Code: GEC 225
Omega Semester
2021/2022
Lead Lecturer: Prof. E. Adetiba
Lecturers: Mrs. Temitope Takpor,
Engr.(Mrs.) A.H. Ifijeh
Teaching Asst.: Omolola Ademola
Module 5
Structures and Unions in C
Language
5.1.0 Structures
— A structure provides a way to store
multiple variables of similar or different
types under one name.
— This makes program more modular as
different variables referring to different
values can be accessed through a single
structure object.
— It is a collection of data items like array,
except that with a structure, the data
items can have different data types.
3 Friday, May 13, 2022
— If you want to store the following information
about a person in a database:
ü Name
ü Citizenship number
ü Salary
— You can easily create different variables:
üstrName
üstrCitNo
üintSalary
to store these information separately.

4 Friday, May 13, 2022


— However, as the database grows, you would
want to store information about multiple
persons.

— Now, you need to create different variables for


each information per person i.e. strName1,
strCitNo1, intSalary1, strName2, strCitNo2,
intSalary2 …

— This approach will create big and messy codes


that will be daunting to read and maintain.

5 Friday, May 13, 2022


— A better approach will be to have a collection
of all related information under a single name
(e.g. Person), and use it for every person.

— With this, the code will be cleaner, readable


and efficient.

— This collection of all related information


under a single name is a structure.

6 Friday, May 13, 2022


5.1.1 Properties of Structures
²Structure is commonly referred to as a user
defined data type.
²C structures allow you to store multiple variables
of any type in one place.
²A structure can contain c’s data types, including
arrays and structures.
²Each variable within a structure is called a
member of the structure.

— This properties make structures ideally


useful for creating databases in c language.
7 Friday, May 13, 2022
5.1.2 Defining a Structure
— The syntax for defining a structure is:
struct structure_name
{
//Statements
};

— struct keyword is used to define a structure,


which is a user defined type.
— Thus, struct defines a new data type, which is
a collection of different types of data.
8 Friday, May 13, 2022
Example 5.1
struct Book
{
char name[15];
int price;
int pages;
};

— Here the struct Book declares a structure to


hold the details of book which consists of three
data fields, namely: name, price and pages.
9 Friday, May 13, 2022
— These data fields are called structure
elements or members.

— Each member can have different data


type, for instance in this case, name is of
char type and price is of int type etc.

— Book is the name of the structure and it


is called structure tag.

10 Friday, May 13, 2022


5.1.3 Declaring a Structure
— It is possible to declare variables of a
structure, after the structure is defined.

— Structure variable declaration is similar to the


declaration of variables of any other data
types.

— Structure variables can be declared in the


following two ways.

11 Friday, May 13, 2022


1. Declaring structure variables separately
Example 5.2
struct Student
{
char name[50];
int age;
char matno[10];
float cgpa;
};
struct Student S1, S2; //declaring variable of student

12 Friday, May 13, 2022


2.Declaring structure variables with structure
definition.
Example 5.3
struct Student
{
char name[50];
int age;
char matno[10];
float cgpa;
} S1, S2;
— S1 and S2 are variables of structure Student.
13 Friday, May 13, 2022
5.1.4 Accessing Members of a
Structure
— Structure member has no meaning
independently.

— In order to assign a value to a structure


member, the member name must be linked
with the structure variable using dot (.)
operator also called period or member access
operator.

14 Friday, May 13, 2022


Example 5.4 (Accessing members of a structure)
struct Book
{
char name[30];
char publisher[15];
int price;
int pages;
}b1,b2;
b1.name = “Programming with C”;
b1.publisher = “CU Press”;
b1.price = 1000;
b1.pages = 200;
— In this code, b1 is a variable of Book type and name,
publisher, price and pages are members of Book.
15 Friday, May 13, 2022
Example 5.5 (Initializing members of a structure)
#include <stdio.h>
int main()
{
struct Patient
{
char name[30];
float height;
int weight;
int age;
int sysbp;
int diabp;
};
//Initialization of Patient structure variable p1
struct Patient p1 = {"Shally Duke", 80.45, 56, 32, 72,118};
16 Friday, May 13, 2022
//Print the assigned values to p1
printf("\n Patient 1 Vitals are:\n\n");
printf("Name: %s\n", p1.name);
printf("Height: %f\n", p1.height);
printf("Weight: %d\n", p1.weight);
printf("Age: %d\n", p1.age);
printf("Systolic BP: %d\n", p1.sysbp);
printf("Diastolic BP: %d\n\n", p1.diabp);
return 0;
}

17 Friday, May 13, 2022


5.1.5 Array of Structure.
— The array of structure in C is used for storing
information about multiple instances of a
structure data type.
— When we declare an array of structure in C
language, each element of the array will
represent a structure variable.

— In order to declare an array of structure, the


structure must first be defined and thereafter,
an array variable of the structure type should
be defined.
18 Friday, May 13, 2022
— The following line of code define an array of
Book of 5 elements. Note that struct Book has
already being defined in Example 5.4

struct Book b[5]

— Each element of array b is of type Book.

19 Friday, May 13, 2022


Example 5.6
//A program to illustrate array of structure
#include<stdio.h>
struct Book
{
char name[30];
char publisher[15];
int price;
int pages;
};
int main()
{
int i;
struct Book b[5];
printf("Enter Records of 5 Books in Your Engineering Bookshelf");
20 Friday, May 13, 2022
for(i=0;i<5;i++)
{
printf("\nEnter Book Name:");
scanf("%s",&b[i].name);
printf("\nEnter Publisher:");
scanf("%s",&b[i].publisher);
printf("\nEnter Price:");
scanf("%d",&b[i].price);
printf("\nEnter Pages:");
scanf("%d",&b[i].pages);
}

21 Friday, May 13, 2022


printf("\n Engineering Books Information List:\n");
for(i=0;i<5;i++)
{
printf("\nName:%s, Publisher:%s, Price:%d,
Pages:%d",b[i].name,b[i].publisher,b[i].price,b[i].pages);
printf("\n");
}
return 0;
}

Action Point:
Run this code in your compiler and provide all required
inputs.
22 Friday, May 13, 2022
5.2.0 Union
— Unions are conceptually similar to structures.

— The syntax of union is also similar to that of


structure. The only differences is in terms of
storage.

— In structure each member has its own storage


location, whereas all members of union uses a
single shared memory location which is equal
to the size of its largest data member.
23 Friday, May 13, 2022
24 Friday, May 13, 2022
— Unions are conceptually similar to
structures.

— Although a union may contain many


members of different types, it cannot
handle all the members at same time.

— A union is declared using union keyword


as shown in the following syntax.

25 Friday, May 13, 2022


Union Syntax
union item
{
int m;
float x;
char c;
}It1;

26 Friday, May 13, 2022


— This example declares a variable It1 of
type union item.

— This union contains three members each


with a different data type.

— However only one of them can be used at


a time. This is due to the fact that only
one location is allocated for a union
variable, irrespective of its size.
27 Friday, May 13, 2022
— The compiler allocates the storage that is
large enough to hold largest variable type
in the union.

— In the union declared in Example 5.7, the


member x requires 4 bytes which is
largest among the members.

— Other members of union will share the


same address.
28 Friday, May 13, 2022
5.2.1 Accessing a Union Member
—The syntax for accessing union
members is similar to accessing
structure members as shown in
the following syntax.

29 Friday, May 13, 2022


Union Syntax
union test
{
int a;
float b;
char c;
}t1;
//to access members of union t
t1.a ;
t2.b ;
t3.c ;

30 Friday, May 13, 2022


Example 5.7//Example to illustrate union
#include <stdio.h>
union person
{
float weight;
int age;
float height;
};
int main( )
{
union person p;
p.weight = 78.5;
p.age = 20;
p.height =5.6;
31 Friday, May 13, 2022
printf("\n%s\n”,p.weight);
printf(”%d\n”,p.age);
printf(”%f\n\n”,p.height);
return 0;
}

— The output of the code when compiled gives:


5.600000
1085485875
5.600000

32 Friday, May 13, 2022


—As shown in the output, the values of
age and weight get corrupted and
only variable height outputs the
expected result.

—This happened because in union, the


only member whose value is
currently stored will have the
memory. 33 Friday, May 13, 2022
—The benefits of union in c
programming are:
vIt occupies less memory compared to
structure.
vIt provides an effective way to use the
same memory location several times by
each of the data members.

34 Friday, May 13, 2022


Assignment 5
Write a C program to create a list of all
students in your program using array of
structure, functions and appropriate
iteration construct. The structure should
contain: Surname, OtherNames, Mat.No.,
RoomNo., Level and CGPA.

Note: This assignment MUST be


submitted on Moodle before the next
class.
35 Friday, May 13, 2022

You might also like