Programming Fundametals in C+ Lec 15
Programming Fundametals in C+ Lec 15
Structures
Structure is a compound data type that contains different variables of different types.
A STRUCT is a C++ data structure that can be used to store together elements of different
data types.
Declaring Structure in C++:
To declare a structure “struct” keyword followed by an identifier. The identifier becomes
the name of the struct.
Example:
struct Student
{
string name;
int id;
int age;
};
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Creating Struct Instance
struct Student
{
string name;
int id;
int age;
};
Struct Student s;
To access the struct members, we use the instance of the struct and the dot (.) operator.
Example
s.age = 27;
return 0;
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
}
Example
struct student
{
cout << "First Student" << endl;
int roll_no;
cout << "roll no : " << p1.roll_no << endl;
string name; cout << "name : " << p1.name << endl;
int phone_number; cout << "phone no : " << p1.phone_number << endl;
}; cout << "Second Student" << endl;
Int main(){ cout << "roll no : " << p2.roll_no << endl;
cout << "name : " << p2.name << endl;
struct student p1 = {1,"Brown",123443};
cout << "phone no : " << p2.phone_number << endl;
struct student p2, p3;
cout << "Third Student" << endl;
p2.roll_no = 2; cout << "roll no : " << p3.roll_no << endl;
p2.name = "Sam"; cout << "name : " << p3.name << endl;
p2.phone_number = 1234567822; cout << "phone no : " << p3.phone_number << endl;
p3.roll_no = 3;
return 0;
}
p3.name = "Addy";
p3.phone_number = 1234567844;
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Task
Write C++ Program to assign data to members of a structure variable and display it.
Let
person name = Iqbal
Age = 34
Salary = 25000
Struct student
{
char name[30];
};
int main()
{
Struct student s;
cout<<“Enter student name”<<endl;
cin.get(s.name,30);
cout<<“Name of student : ”<<s.name<<endl;
}
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Structure and Function
Example:
struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
Write a program to store and print the roll no., name , age, department name and marks of
a student using structures.
4 students data using structure.