You are on page 1of 4

Lecture 4 :Structures in C++ Class Examples

1. A Simple Structure declaration

2. Example 2
3. Example 3

#include<iostream>
using namespace std;

struct PersonRec{
string lastName;
string firstName;
int age;
};

int main( ){
PersonRec thePerson;
cout << "Enter first name: ";
cin >> thePerson.firstName;
cout << "Enter last name: ";
cin >> thePerson.lastName;
cout << "Enter age: ";
cin >> thePerson.age;

cout << "\n\nHello " << thePerson.firstName << ' '<< thePerson.lastName << ". How are you?\n";
cout << "\nCongratulations on reaching the age of "<< thePerson.age << ".\n";
return 0;
}

4. Example 4

#include<iostream>
using namespace std;

struct GradeRec{
float percent;
char grade;
};

struct StudentRec
{
string lastName;
string firstName;
int age;
GradeRec courseGrade;
};
int main()
{
StudentRec student;
cout << "Enter first name: ";
cin >> student.firstName;
cout << "Enter last name: ";
cin >> student.lastName;
cout << "Enter age: ";
cin >> student.age;
cout << "Enter overall percent: ";
cin >> student.courseGrade.percent;
if(student.courseGrade.percent >= 90){
student.courseGrade.grade = 'A';
}
else if(student.courseGrade.percent >= 75){
student.courseGrade.grade = 'B';
}
else{
student.courseGrade.grade = 'F';
}

cout << "\n\nHello " << student.firstName << ' ' << student.lastName
<< ". How are you?\n";
cout << "\nCongratulations on reaching the age of " << student.age<< ".\n";
cout << "Your overall percent score is "
<< student.courseGrade.percent << " for a grade of "
<< student.courseGrade.grade;

return 0;
}

5. Example 5
6. Example 6

#include<iostream>
using namespace std;

struct coord {
int x;
int y;
};

struct rectangle {
struct coord topleft;
struct coord bottomrt;
};

int main () {
int length, width;
long area;

struct rectangle mybox;


mybox.topleft.x = 0;
mybox.topleft.y = 0;
mybox.bottomrt.x = 100;
mybox.bottomrt.y = 50;

width = mybox.bottomrt.x-mybox.topleft.x;
length = mybox.bottomrt.y-mybox.topleft.y;

area = width * length;


cout<<"The area is "<<area<<"units.";

return 0;
}

You might also like