Slide 3
Slide 3
1 Ghalib University
Table of Contents
1. Structure
2. Structure variable
3. Arrays of Structures
4. Nested Structures
2 Ghalib University
Structure
C++ allows you to group several variables together into a single
Structure is same like array but in array we can store only same
3 Ghalib University
Structure
struct is a key word used for defining structure.
type is any valid data type.
a, b, c are the name of variables.
Example: To declare Student structure.
struct students
{
int roll_no;
char name[40];
int marks;
};
return 0;
}
5 Ghalib University
Structure variable
A variable which is declared as structure type is called structure
variable.
Stucture_neme variable_name;
students s1;
6 Ghalib University
Accessing Members of Structure
The dot operator(.) allows you to access structure members in a
program.
7 Ghalib University
Example of Structure variable
#include <iostream>
using namespace std;
struct students{
int roll_no;
char name[40];
int marks;};
int main()
{
students s1;
cout<<"please enter the roll number :";
cin>>s1.roll_no;
cout<<"please enter the name :";
cin>>s1.name;
cout<<"please enter the marks :";
cin>>s1.marks;
return 0;
}
8 Ghalib University
Initializing a Structure
Assigning values to a structure variables at the time of
structure.
Students S1={20,”Mirwais”,75};
9 Ghalib University
Arrays of Structures
Arrays of structures can simplify some programming tasks.
10 Ghalib University
Structure Array Initialization
Like other arrays the structure array can also be initialized.
struct students
{
int roll;
char name[20];
int total;
};
students S1[3]=
{{101,”Ferdows”450},{102,”Zobair”,500},{103,”Kabir”,650} }
11 Ghalib University
Nested Structures
It’s possible for a structure variable to be a member of another
structure variable.
12 Ghalib University
Example of Nested Structures
#include<iostream>
using namespace std;
struct Price
{
double wholesale;
double retail;
};
struct item
{
int code;
string description;
Price p;
};
int main()
{ item item1;
item1.p.wholesale = 100.0;
item1.p.retail = 150.0;
cout<<item1.p.wholesale<<endl;
cout<<item1.p.retail<<endl;
return 0;
}
13 Ghalib University
Any question…?????????????
14 Ghalib University