Structures Programming
Structures Programming
CLO1:
Apply program structure and debugging process in C++
programming language accordingly.
CLO2:
Design programs using appropriate control structures,
arrays, structures, functions and pointers.
CLO3:
Solve problems using C++ programming language
environment with proper coding style guidelines and take in
the security issues into consideration.
What is a Structure ?
• A structure is a group of data elements grouped
together under one name.
struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
How to Declare Structures
• Explanation for the syntax
- structure_name is a name for the structure type, object_name
can be a set of valid identifiers for objects(variables) that have
the type of this structure.
- Within braces { } there is a list with the data members, each
one is specified with a type and a valid identifier as its name.
- Once a data structure is declared, a new type with the
identifier specified as structure_name is
created and can be used in the rest of
the program as if it was any other type.
How to Declare Structures
Sample :
keyword
structure name
struct Employer
{
int emp_id;
char emp_name[30]; structure members
float salary;
};
How to Declare Structures
• In the previous sample, it is seen that variables of
different types such as int, float and char are
grouped in a single structure name Employer
• After declaring the structure, the next step is to define
a structure variable
How to Declare Structures
• This is similar to variable declaration.
• For variable declaration, data type is defined
followed by variable name:
int name;
• For structure variable declaration, the data type is
the name of the structure followed by the structure
variable name .
How to Declare Structures
• From the previous sample
Structure name
Employer one;
Structure
variable name
How to Declare Structures
What happens when this is defined?
struct Employer {
int emp_id;
char emp_name[30];
float salary;
};
Employer one;
How to access structure
members?
• To access structure members, the operator used is
the dot operator denoted by (.)
• If we want to assign 2000 for the structure member
salary :
one.salary = 2000;
void main()
{
struct Course
{
char code[6];
char course_name[30];
int credit_hour;
}subject;
cout<<"Enter code:";
cin>>subject.code;
cout<<"Code:"<<subject.code<<endl;
cout<<"Course name:"<<subject.course_name<<endl;
cout<<"Credit hour:"<<subject.credit_hour<<endl;
}