4. Calculate Distance
Write a program that represents the distance in
the form of a structure containing meters, and
centimeters
Define 3 variables and input their values, as
follows:
The first value from the user.
The second value from initialization.
The third value is the result of addition of the
other two values.
6. int main()
{
dist d1, d2, d3;
// Enter the values of the first variable members
cout << "Enter the values of the first variable: meters
then centimeters" <<endl;
cin >> d1.meters >> d1.centimeters;
// Initialize the second variable members
d2.meters = 15;
d2.centimeters = 40;
// Add the first and second variable members adn put
the result in the third variable
d3.meters = d1.meters + d2.meters;
d3.centimeters = d1.centimeters + d2.centimeters;
7. // Put the third variable in the correct meters and
centimeters format
while (d3.centimeters >= 100)
{
d3.meters++;
d3.centimeters -= 100;
}
//Display the third variable members
cout<< d1.meters << "." << d1.centimeters << " + "
<< d2.meters << "." << d2.centimeters << " = "
<< d3.meters << "." << d3.centimeters << endl;
}
8. Room Area
Write a program that creates a data structure
that stores the 2 dimensions of a room (its
length and width), putting into account that the
length and width are both members of the
distance struct represented in program1, and
then outputs the area of the room in square
meters.
9. #include <iostream>
using namespace std;
void main()
{
//Distance struct that we have seen before!
struct distance
{
int meters;
int centimeters;
};
//Define Room Struct
struct room
{
//member length is another struct !!
distance length;
distance width;
distance height;
};
10. //Declare a main variable
room living;
//initialize variable members
living.length.meters = 10;
living.length.centimeters = 17;
living.width.meters = 12;
living.width.centimeters = 10;
//Calculate approximate length and width
int approxLength = living.length.meters +
living.length.centimeters / 100.0;
int approxWidth = living.width.meters +
living.width.centimeters / 100.0;
//calculate area and display it..
cout<<"Area : "<< approxLength * approxWidth<<" square
meters. "<<endl;
}
CodeTip
Braces
11. Array of Student
Write a program that represents the students’
data by name (char array), id (int) and 6 grades.
The user should input the data of 3 students
(array of struct), and then the program should
output the sum of grades of each student beside
his name.
13. for(int i = 0; i < 3; i++)
{
//read id
cout<<"Enter the id of student"<<i + 1<<": ";
cin>>s[i].id;
cin.ignore();
//read name
cout<<"Enter the name of student"<<i + 1<<endl;
gets(s[i].name);
//read 6 grades
cout<<"Enter the grades of student "<<i + 1<<": ";
for(int j = 0 ; j < 6 ; j++)
{
cin>>s[i].grades[j];
}
}
14. int sum;
for(int i = 0 ; i < 3 ; i++)
{
sum = 0;
cout<<"Sum of grades of student"<<s[i].name<<": ";
//calculate total grade for each student
for(int j = 0 ; j < 6 ; j++)
{
sum += s[i].grades[j];
}
cout<<sum<<endl;
}
}