If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Problem: Write a program that uses a structure to represent a rectangle. Implement functions to calculate the area and perimeter of the rectangle. The program should prompt the user to input the dimensions of the rectangle and display the calculated area and perimeter.
cppCopy code
#include <iostream>
// Structure representing a rectangle
struct Rectangle {
double length;
double width;
};
// Function to calculate the area of a rectangle
double calculateArea(const Rectangle& rectangle) {
return rectangle.length * rectangle.width;
}
// Function to calculate the perimeter of a rectangle
double calculatePerimeter(const Rectangle& rectangle) {
return 2 * (rectangle.length + rectangle.width);
}
int main() {
Rectangle rectangle;
std::cout << "Enter the length of the rectangle: ";
std::cin >> rectangle.length;
std::cout << "Enter the width of the rectangle: ";
std::cin >> rectangle.width;
double area = calculateArea(rectangle);
double perimeter = calculatePerimeter(rectangle);
std::cout << "Area of the rectangle: " << area << std::endl;
std::cout << "Perimeter of the rectangle: " << perimeter << std::endl;
return 0;
}
In this example, we define a structure called Rectangle that represents a rectangle with length and width as its attributes.
The program includes two functions: calculateArea and calculatePerimeter. These functions take a const reference to a Rectangle object and calculate the area and perimeter of the rectangle using the formulae length * width and 2 * (length + width), respectively.
In the main function, we declare a Rectangle variable rectangle. We prompt the user to input the length and width of the rectangle. We then call the calculateArea and calculatePerimeter functions, passing the rectangle object as an argument, and store the calculated area and perimeter in the respective variables.
Finally, we print the calculated area and perimeter using std::cout.
You can modify and expand upon this code to practice implementing additional functions, working with structures, or exploring different calculations or properties of objects using structures and functions.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support