Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

Structs - II

Structs – revision
Assignment Statement
Relational operator
Arrays in Structs
Structs in Arrays
Nested Structs
Setter Getter Function
Constructors
Access Modifier
Revision - Definition
• A student record may consists of the

• student’s name,

• student ID, GPA,

• courses taken, and

• course grades.

• These components are all of different types. For example, the

• student’s name is a string, and the

• GPA is a floating-point number.

• One cannot use an array to group all of the items associated with a

student as they are different.

• C++ provides a structured data type called struct to group items of


Struct

A collection of a fixed number of


components in which the
components are accessed by name.
The components may be of different
types.
Example
struct studentType {
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
} tempStudent;
Here tempStudent is an instance of type studentType or a varaible of type stduentType
This could be declared in the main function or with the struct as shown here.
struct variable becomes a global variable and thus can be accessed anywhere in the program
Assignment Statements - Structs
#include <iostream>
using namespace std;

struct studentType {
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
} Student1, Student2;

int main(){

Student1.firstName ="Nida";
Student1.lastName = "Khan";
Student1.courseGrade = 'A';
Student1.testScore = 75;
Student1.programmingScore = 80; Copies all the contents of
Student1.GPA = 3.65;
Student 1 to Student 2
//Assignment Statement
Student2=Student1;

cout<<Student2.firstName<<endl;
cout<<Student2.lastName<<endl;

return 0;}
#include <iostream>
using namespace std;

struct studentType {
Relational Operators eg.,
string firstName;
string lastName;
‘==‘
char courseGrade;
int testScore;
int programmingScore;
double GPA;
} Student1, Student2;

int main(){
Student1.firstName ="Nida";
Student1.lastName = "Khan";
Student1.courseGrade = 'A';
Student1.testScore = 75;
Student1.programmingScore = 80;
Student1.GPA = 3.65;

Student2=Student1; // Assignment Operator

//Relational Operators
if (Student2==Student1) Relational Operators do not work
cout<<"Student1 and Student2 are same"<<endl;

cout<<Student2.firstName<<endl;
cout<<Student1.firstName<<endl;
return 0;}
#include <iostream>
using namespace std;

struct studentType {
string firstName;
Functions – Pass By
string lastName;
char courseGrade;
int testScore;
Reference
int programmingScore;
double GPA;
} Student1, Student2;

void readIn(studentType &student) {


int score;
score = (student.testScore + student.programmingScore) / 2;
if (score >= 90) student.courseGrade = 'A';
else if (score >= 80) student.courseGrade = 'B';
else if (score >= 70) student.courseGrade = 'C';
else if (score >= 60) student.courseGrade = 'D';
else student.courseGrade = 'F';
}
void printStudent(studentType &student) {
cout << student.firstName << " " << student.lastName << " " << student.courseGrade<< " " << student.testScore<< " " <<
student.programmingScore<< " " << student.GPA << endl;
}

int main(){
Student1.firstName ="Nida";
Student1.lastName = "Khan";
Student1.courseGrade = 'A'; Functions – Pass By Value
Student1.testScore = 75;
Student1.programmingScore = 80;
Change call as follows:
Student1.GPA = 3.65;
void readIn(studentType student)
readIn(Student1);
printStudent(Student1);
return 0;}
Arrays - Structs
#include <iostream>
using namespace std;

const int ARRAY_SIZE = 1000; Arrays in Structs


struct listType{

int listElem[ARRAY_SIZE]; //array containing the list


int listLength;//length of the list
}; Defining Arrays in Structs
int main()
{
listType intList; // defining listType
intList.listLength = 0; // defining index
intList.listElem[0] = 12; //entering value at 0 index and so on.
intList.listLength++;
intList.listElem[1] = 37;
intList.listLength++;

cout<<intList.listElem[0]<<endl;
cout<<intList.listElem[1]<<endl;

return 0;
}
Write a Program that does
Sequential Search for a element of
array and returns the index
Function for Sequential Search
int seqSearch(const listType& list, int searchItem) {

int loc;

bool found = false;

for (loc = 0; loc < list.listLength; loc++) if (list.listElem[loc] == searchItem)

found = true;

break;

if (found) return loc;


Program – Sequential Search
#include <iostream>
using namespace std;
int main()
const int ARRAY_SIZE = 1000; {
listType intList; // defining listType
struct listType{ intList.listLength = 0; // defining index
int listElem[ARRAY_SIZE]; //array containing the list intList.listElem[0] = 12;
int listLength;//length of the list intList.listLength++;
intList.listElem[1] = 37;
int seqSearch(const listType& list, int searchItem) { intList.listLength++;
int loc;
bool found = false; cout<<intList.listElem[0]<<endl;
cout<<intList.listElem[1]<<endl;
for (loc = 0; loc < list.listLength; loc++) if (list.listElem[loc] == searchItem)
{ int index = intList.seqSearch(intList, 37);
found = true; cout <<index<<endl;
break; return 0;
} }
if (found) return loc;
else
return -1;
}
};
Structs in Arrays
• Each Tuple is representing a struct
• Employees array with each tuple representing
struct
Example
• What if you want to represent ‘n’ employees
having multiple variables of different types.
struct employeeType {

string firstName; Employee type struct


Now how to represent ‘n’
string lastName; Employees. Lets say n=50;

int personID;

string deptID;

double yearlySalary;
employeeType employees[50];
double monthlySalary;
#include <iostream>
using namespace std;

struct employeeType {
string firstName;
Example for n=4
string lastName;
int personID;
string deptID;
double yearlySalary;
double monthlySalary;
double yearToDatePaid;
double monthlyBonus;
};

int main()
{
employeeType employee[4];
employee[0].firstName = "Nisar";
employee[1].firstName = "Nisar";
employee[2].firstName = "Nisar";
employee[3].firstName = "Nisar";

int i;
for (i=0;i<4;i++){
cout<<employee[i].firstName<<endl;
}

return 0;
}
struct employeeType {
string firstname;
string middlename;
string lastname; Example – Nested Struct
string empID;
string address1;
string address2;
string city;
• Consider
string state;
string zip;
employee
int hiremonth; struct with a
int hireday;
int hireyear; few attributes
int quitmonth;
int quitday; • Suggest a
int quityear;
string phone; better
string cellphone;
string fax;
representation
string pager;
string email;
string deptID;
double salary;
};
Nested Structs
struct nameType {

struct employeeType { string first;

nameType name; string middle;


string empID; string last;
addressType address; // struct addressType
dateType hireDate; //struct dateType };

dateType quitDate; //struct dateType struct addressType {


contactType contact; //struct contactType string address1;
string deptID;
double salary; string address2;

}; string city;

string state;

string zip;

};

struct dateType {

int month;

int day;

int year;
#include <iostream>
using namespace std;

struct employeeType {
nameType name;
string empID;
Program
addressType address; // struct addressType
dateType hireDate; //struct dateType
dateType quitDate; //struct dateType
contactType contact; //struct contactType
string deptID;
double salary;
};
struct nameType {
string first;
string middle; int main()
string last;
};
{
struct addressType { employeeType newEmployee;
string address1;
string address2; newEmployee.name.first = "Rashid";
string city;
string state;
newEmployee.name.middle = "Ayaan";
string zip; newEmployee.name.last = "Rizwan";
};
struct dateType { return 0;
int month;
int day;
}
int year;
};
struct contactType {
string phone; What will be the output of this program?
string cellphone;
string fax;
string pager;

};
string email; Will not compile ….
#include <iostream>
using namespace std;

struct nameType {
string first;
string middle;
Program - revised
string last;
};
struct addressType {
string address1;
string address2; int main()
string city;
string state; {
string zip;
};
employeeType newEmployee;
struct dateType { newEmployee.name.first = "Rashid";
int month;
int day; newEmployee.name.middle = "Ayaan";
};
int year; newEmployee.name.last = "Rizwan";
struct contactType { return 0;
string phone;
string cellphone; }
string fax;
string pager;
string email;
};

struct employeeType {
nameType name;
string empID;
addressType address; // struct addressType
dateType hireDate; //struct dateType
dateType quitDate; //struct dateType
contactType contact; //struct contactType
string deptID; Nested Struct should come after independent struts
double salary;
};
Setter – Getter Functions
struct point
{ Setting and Getting Values
int x;
int y;
point() //constructor function called automattically when you declare an object of type point
{
x = 0;
y = 0;
}
void setX(int a) //This is a setter function because it is setting a value of a varibale of struct
{
x = a;
}
void setY(int b) //This is a setter function because it is setting a value of a varibale of struct
{
y = b;
}
int getX() //This is called a getter function because it is giving us the value of a varibale of struct
{
return x;
}
int getY()//Similarly another getter function.
{ return y;}

};
#include <iostream>
using namespace std;
struct point
{
Program
int x;
int y;
point() //constructor function called automattically when you declare an object of type point
{
x = 0;
y = 0;
}
point(int s,int q)
{ int main()
x=s; {
y=q; point p1,p2(2,7);
cout<<p1.x<<endl;
} cout<<p1.y<<endl;
void setX(int a) //This is a setter function because it is setting a value of a varibale of struct cout<<p2.x<<endl;
{ cout<<p2.y<<endl;
x = a;
} p1.setX(3);
void setY(int b) //This is a setter function because it is setting a value of a varibale of struct p1.setY(4);
cout<<p1.x<<endl;
{ cout<<p1.y<<endl;
y = b;
} int x1=p1.getX();
int getX() //This is called a getter function because it is giving us the value of a varibale of struct int y1=p1.getY();
{ cout<<x1<<endl;
return x; cout<<y1<<endl;
} return 0;
int getY()//Similarly another getter function. }
{ return y;}
};
struct inventory {
int part_no;
float cost;
Setter/Getter STRUCT
float price;
Arrays
inventory()
{
part_no=0;
cost=0; //Inside main program or function
price=0; //setter for array
}
table[0].setpart_no(6);
inventory(int a,float b,float c) table[0].getpart_no(table[0].part_no);
{ table[0].print();
part_no=a;
cost=b;
price=c;
}
void setpart_no(int a)
void print() {
{
cout<<“part_no”<<part_no<<endl;
part_no=a;
cout<<“cost”<<cost<<endl; };
cout<<“price”<<price<<endl;
} //getter
int getpart_no()
}; {
return part_no;
};
Function Returning STRUCTS
• Suppose you add two points, p1 and p2
• Each point has x and y values
• The addition will results into another point
with x and y values, p3=p1+p2
• One can write a function add that returns
another struct p3.
Function Return Type (Struct) “ADD”
//GENERAL STRUCTURE OF A FUNCTION
 
// return type function_name(parameter 1,parameter_2......parameter_n)
//{
//function body
//return statement here
//} 
point add(point a, point b)
{
//this will return an point object
//this is a pass by value function
point r;
r.x = a.x + b.x;
r.y = a.y + b.y;
return r;
‘r’ is another STRUCT and also the return type
}
point subtract(point a,point b)
{ Other Functions
point r;
r.x = a.x - b.x ;
r.y = a.y - b.y ; point divide(point a,point b)
return r; {
} point r;
point multiply(point a,point b) r.x = a.x/b.x;
r.y = a.y/b.y;
{
return r;
point r; }
r.x = a.x*b.x;
r.y = a.y*b.y;
return r;
}
#include <iostream>
using namespace std;

Program
//this time I declared point definition globally so that it is used throughout the program
struct point
{
int x;
int y;
point() //constructor function called automatically when you declare an object of type point
{
x = 0;
y = 0; int main()
}
void setX(int a) //This is a setter function because it is setting a value of a varibale of struct {
{
x = a; point p1;
}
void setY(int b) //This is a setter function because it is setting a value of a varibale of struct
p1.x = 9;
{ p1.setY(18);
y = b;
}  
int getX() //This is called a getter function because it is giving us the value of a varibale of struct
{
point p2;
return x; p2.setX(1);
}
int getY()//Similarly another getter function. p2.y = 2;
{
return y;  
};
}
point add_val;
//Don't need these definitions now need for functions returning structs cout<<"Showing result of addition:";
point add(point a,point b);
add_val = add(p1,p2);
point add(point a,point b)
{ //this will return an point object
cout<<add_val.x<<endl;
//this is a pass by value function cout<<add_val.y<<endl;
point r;
r.x = a.x + b.x; cout<<endl;
r.y = a.y + b.y;
return r; return 0;
}
}
Access Modifiers: Private - Public
#include <iostream>
using namespace std;

struct mystruct {
// public by default
int f() {
return a; }
private:
Please Note:
// private data member
int a =10;
};
STRUCTS are by default PUBLIC
Unless
int main() Declared PRIVATE
{
mystruct y;
//cout << "a" <<y.a<< endl;
cout << "Access a through function "<< y.f() << endl;

return 0;
}
Sample Code – STRUCTS Pointers/
Private - Public
#include <iostream>
using namespace std;
int main()
struct mystruct { {
mystruct y;
//cout << "a" <<y.a<< endl;
// public by default cout << "Access b " << y.b << endl;
int b =5; cout << "Access a through function a="<< y.f() << endl;

int f() { //Pointers to struct


mystruct *ptr = &y;
return a; } // cout << "Access Through Pointer a =" << ptr -> a << endl;
cout << "Access Through Pointer b = " << ptr -> b << endl;
cout <<"Aternate way Access Through Pointer b =" << (*ptr).b << endl;
private:
cout << "Access Through Pointer a =" << ptr -> f() << endl;
// private data member cout <<"Aternate way Access Through Pointer a =" << (*ptr).f() << endl;
int a =10;
}; return 0;
}

You might also like