Lecture-27 (25-11-2023)
Lecture-27 (25-11-2023)
MA144:
Computer Programming
Lecture-27
Structures-1
Structure
What is a Structure?
• It is a convenient construct for representing a group of
logically related data items.
Examples:
Student name, roll number, and marks.
Real part and imaginary part of a complex number.
• Structures help in organizing complex data in a more
meaningful way.
• The individual structure elements are called members.
• This is first user-defined data-type.
Structure Definition
struct name_of_structure
{ data_type member_name1;
data_type member_name2;
data_type member_name3;
};
Example
struct student
{ char name[30];
int rollNo;
char grade;
};
struct is the required keyword
• Do not forget the ; at the end of the structure definition
• The individual members can be ordinary variables,
pointers, arrays, or other structures (any data-type)
• The member names within a particular structure must
be distinct from one another
• A member name can be the same as the name of a
variable defined outside of the structure
Defining structure variables
#include<iostream> #include<iostream>
using namespace std; using namespace std;
struct student struct student
{ char name[30]; { char name[30];
int rollNo; int rollNo;
char grade; char grade;
}; }x,y;
int main() int main()
{ student x,y; {
return 0; return 0;
} }
Accessing structure members
• The members of a structure are accessed individually,
as separate entities.
• A structure member can be accessed by writing
<structure-variable-name>.<member-name>
x.name;
x.rollNo;
x.grade;
Structure Initialization
Structure variables may be initialized following similar rules of an array.
The values are provided within braces separated by commas.
#include<iostream>
#include<string>
using namespace std;
struct student
{ int roll;
string name;
};
int main()
{ student x={24,"hai"};
cout<<"\n student x details: "<<endl;
cout<<" Roll: "<<x.roll<<endl;
cout<<" student name: "<<x.name;
return 0;}
Run-time initialization
#include<iostream>
#include<string>
using namespace std;
struct student
{ int roll;
string name;
}x;
int main()
{ cout<<"enter roll of x: ";
cin>>x.roll;
cout<<" enter name of student x: ";
cin>>x.name;
cout<<"\n student x details: "<<endl;
cout<<" Roll: "<<x.roll<<endl;
cout<<" student name: "<<x.name;
return 0;}
Assignment of Structure Variables
• A structure variable can be directly assigned to another
variable of the same type.
• All the individual members get assigned / copied.
• Structures can be copied directly – even if they contain
arrays
• But, two structure variables cannot be compared
for equality or inequality