Practice Cpp Class

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Certainly! Here's a practice exercise to help you work on creating and using classes in C++:

Problem: Create a class called Rectangle that represents a rectangle. Implement member functions to calculate the area and perimeter of the rectangle. Write a program to create rectangle objects, set their dimensions, and display their area and perimeter.

cppCopy code

#include <iostream> // Class representing a Rectangle class Rectangle { private:    double length;    double width; public:    // Constructor    Rectangle(double len, double wid) {        length = len;        width = wid;    }    // Function to calculate the area of the rectangle    double calculateArea() {        return length * width;    }    // Function to calculate the perimeter of the rectangle    double calculatePerimeter() {        return 2 * (length + width);    } }; int main() {    // Create Rectangle objects    Rectangle rectangle1(5.0, 3.0);    Rectangle rectangle2(7.5, 4.2);    // Calculate and display the area and perimeter of rectangle1    double area1 = rectangle1.calculateArea();    double perimeter1 = rectangle1.calculatePerimeter();    std::cout << "Rectangle 1:\n";    std::cout << "Area: " << area1 << std::endl;    std::cout << "Perimeter: " << perimeter1 << std::endl;    // Calculate and display the area and perimeter of rectangle2    double area2 = rectangle2.calculateArea();    double perimeter2 = rectangle2.calculatePerimeter();    std::cout << "Rectangle 2:\n";    std::cout << "Area: " << area2 << std::endl;    std::cout << "Perimeter: " << perimeter2 << std::endl;    return 0; }

In this example, we create a Rectangle class that represents a rectangle with private member variables length and width.

The Rectangle class has a constructor that takes the length and width as parameters and initializes the member variables.

The class also includes member functions calculateArea and calculatePerimeter that calculate the area and perimeter of the rectangle, respectively.

In the main function, we create two Rectangle objects, rectangle1 and rectangle2, with different dimensions using the constructor.

We then call the calculateArea and calculatePerimeter functions on each object to calculate their respective area and perimeter. Finally, we display the area and perimeter of each rectangle using std::cout.

By running the program, you will see the output that displays the area and perimeter of the rectangles.

2. Essential C and Cpp Concepts

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support