You are on page 1of 14

UNIT

4 STRUCTURES

IT 105 Computer Programming 2


LESSON 1
Introduction to Structures

IT 105 Computer Programming 2


Structures
A structure is a collection of related elements, possibly of
different types, having a single name.
It allows you to wrap one or more variables with different
data types under a single name.

In other programming languages, structures are called


records, and members are known as fields.

IT 105 Computer Programming 2


Structures
For example, you want to refer to student with multiple data like
name,course, age, grade :

Student structure name


(group name)
Name Course Age Grade field names
(members)
Ana BSIT 18 90
John BIT 19 92
Cathy BSM 18 89

string string int int

IT 105 Computer Programming 2


Structure Definition

Structure definition consists of the reserved word struct, the name


of the structure (tag) ,and the symbol {,field list, the symbol }.

struct structure name


{
field list
(structure members)
};

IT 105 Computer Programming 2


Structure Definition

Example :
struct student structure name
{
char name[20];
field list
char course[5];
(structure members)
int age;
int grade;

};

IT 105 Computer Programming 2


Structure Variable

A structure variable is variable declared with struct as the


data type capable of holding multiple data.

A struct is a data type with a number of components (or


fields), can contain any valid data types like int, char, float even
arrays or even other structures.

IT 105 Computer Programming 2


Structure Variable Declaration
To declare a variable of type struct:

struct structure name identifier;

struct student stud;


* stud is the name of the variable of type struct which means that this
variable can hold values of all members of structure student, as illustrated
below:

stud name course age grade

IT 105 Computer Programming 2


Structure Variable Initialization
To initialize a variable of type struct:

struct student stud ={ “Ana”, ”BSIT”,18,90};


Ana BSIT 18 90

name course age grade

members of structure student

IT 105 Computer Programming 2


Accessing Members of Structure

Input name cin.getline(stud.name,20);


Display age cout <<stud.age;
Test if grade is if (stud.grade>=75)
passed or failed
cout<<“passed”;

struct student stud;

IT 105 Computer Programming 2


Sample Program

IT 105 Computer Programming 2


Sample Program

IT 105 Computer Programming 2


Sample Program
A program that computes the salary of employee based on
hours worked and rate per hour.

//Structure Definition
struct employee
{
double hours;
double rate; // or can be written as double hours,rate, salary;
double salary;
};
//Structure Variable Declaration

struct employee emp;

IT 105 Computer Programming 2


Sample Program

IT 105 Computer Programming 2

You might also like