Using C++
1. Create a program that asks the user to create 5 triangles, asking for 5 bases and 5 heights (you can use an array), have a function to print the triangle bases, heights, and areas
2. Create a structure for the Triangle that holds the base and height of the triangles. Ask the user for 5 triangles, and print them.
3. Create an array of 5 structures - ask the user for 5 triangles, and then print the array.
1.
#include <iostream>
using namespace std;
void print(int base[5], int height[5]) // function to print base,
height and area
{
for(int i = 0; i < 5; i++)
{
cout << "Triangle " << i+1 << ":" <<
endl;
cout << "Base: " << base[i] << endl;
cout << "Height: "<< height[i] << endl;
cout << "Area: "<< (base[i]*height[i])/2 << endl;
// area is (1/2)*(base*height)
}
}
int main()
{
int base[5], height[5]; // array of size 5 for base and
height
cout << "Enter the base of 5 triangles: ";
for(int i = 0; i < 5; i++)
{
cin >> base[i];
}
cout << "Enter the height of 5 triangles: ";
for(int i = 0; i < 5; i++)
{
cin >> height[i];
}
print(base,height); // function call
return 0;
}
2.
#include <iostream>
using namespace std;
struct Triangle{ // Triangle structure
int base;
int height;
};
void print(struct Triangle triangle) // function to print base and
height
{
cout << triangle.base << " " << triangle.height
<< endl;
}
int main()
{
struct Triangle triangle1, triangle2, triangle3, triangle4,
triangle5; // 5 Triangle objects
// Input for 5 triangles
cout << "Enter base and height for first triangle: ";
cin >> triangle1.base >> triangle1.height;
cout << "Enter base and height for second triangle: ";
cin >> triangle2.base >> triangle2.height;
cout << "Enter base and height for third triangle: ";
cin >> triangle3.base >> triangle3.height;
cout << "Enter base and height for fourth triangle: ";
cin >> triangle4.base >> triangle4.height;
cout << "Enter base and height for fifth triangle: ";
cin >> triangle5.base >> triangle5.height;
cout << "Triangle 1 base and height: ";
print(triangle1);
cout << "Triangle 2 base and height: ";
print(triangle2);
cout << "Triangle 3 base and height: ";
print(triangle3);
cout << "Triangle 4 base and height: ";
print(triangle4);
cout << "Triangle 5 base and height: ";
print(triangle5);
return 0;
}
3.
#include <iostream>
using namespace std;
struct Triangle{ // Triangle structure
int base;
int height;
};
void print(struct Triangle obj[5]) // function to print base and
height
{
cout << "Base and height of 5 triangles are: " <<
endl;
for(int i = 0; i < 5; i++)
{
cout << obj[i].base << " " << obj[i].height
<< endl;
}
}
int main()
{
struct Triangle obj[5]; // array of 5 triangle objects
cout << "Enter base of 5 triangles: ";
for(int i = 0; i < 5; i++)
{
cin >> obj[i].base;
}
cout << "Enter height of 5 triangles: ";
for(int i = 0; i < 5; i++)
{
cin >> obj[i].height;
}
print(obj); // function called
return 0;
}
Please give an upvote if you liked my solution. Thank you :)
Get Answers For Free
Most questions answered within 1 hours.