Chapter 2 - StructuresConcise
Chapter 2 - StructuresConcise
Science
Chapter Two
Structures
1. What is a Structure?
A structure is a collection data structures that contains member elements or member variables known
as data members with similar or dissimilar data types that can be referred with single or group
name and member name.
struct structname
{
datatype1 Membervariable1;
datatype2 Membervariable2;
“ “
datatypeN MembervariableN;
};
The data members (synonym for member variables) of a structure won’t actually be
created until a variable based on the structure is created. Example defining a student
struct,
struct student
{
int id;
char name[15];
};
Example: The follow defines a structure called ‘date’ which contains three ‘int’ member
variables: ‘day’, ‘month’, and ‘year’:
struct date {
int day;
int month;
int year;
};
struct date
{
int day, month, year;
};
Note: You cannot initialize member variables in a structure definition.
The following is wrong and will not compile:
struct date{
-1-
Assosa University Department Of Computer
Science
int day = 24, month = 10, year = 2001;
};
#include <iostream.h>
struct date {
int day, month, year;
};
int main() {
date d; //creating structure object d to access the data members in the
structure date
return 0;
}
student std1;
date birthday;
int i;
The above statements are similar in nature because both declare a variable of a
given type. The former is a built in type, which is integer while the later
declares a variable type of user-defined type. std1 will have the characteristics
of representing id and name of a student.
Example: For reading and displaying values to and from structure s1.
-2-
Assosa University Department Of Computer
Science
Example:-a program that creates student struct and uses it to The above program shows you how to capture data in student variables.
store student information. Example 2: This program demonstrates using member variables for user input,
output, and mathematical operations.
cout<<endl<<b1.id<<"\t"<<b1.title;
cout<<endl<<b2.id<<"\t"<<b2.title;
-3- return 0;
}
Assosa University Department Of Computer
Science
-4-