Circle Class in C++ to Calculate Area and Perimeter

In this exercise, you will develop a C++ class called "Circle" that can calculate the area and perimeter of a circle. The class will have attributes such as the radius, and it will contain member functions to calculate both the area and the perimeter based on the radius. This task helps you practice working with classes, constructors, and member functions in C++. It will also give you a better understanding of how to implement mathematical calculations using a class structure.

Group

Object-Oriented Programming in C++

Objective

1. Define a class called "Circle" with the attribute "radius" (double).
2. Add a constructor that takes the radius as a parameter.
3. Implement two member functions: one to calculate the area and another to calculate the perimeter.
4. In the main function, create an object of the Circle class with a given radius and display the area and perimeter.

Develop a Circle class that calculates the area and perimeter of a circle.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include the standard input/output library
#include <cmath>      // Include the cmath library to use mathematical functions like M_PI
using namespace std;

// Define the 'Circle' class
class Circle {
private:
    double radius;  // Private attribute for radius

public:
    // Constructor to initialize the 'Circle' object with a radius
    Circle(double r) {
        radius = r;  // Set the radius to the passed value
    }

    // Member function to calculate the area of the circle
    double calculateArea() {
        return M_PI * radius * radius;  // Use the formula πr^2 to calculate the area
    }

    // Member function to calculate the perimeter (circumference) of the circle
    double calculatePerimeter() {
        return 2 * M_PI * radius;  // Use the formula 2πr to calculate the perimeter
    }
};

int main() {
    // Create an object of the 'Circle' class with a radius of 5
    Circle circle1(5);

    // Output the area and perimeter of the circle
    cout << "Area of the circle: " << circle1.calculateArea() << endl;  // Print area
    cout << "Perimeter of the circle: " << circle1.calculatePerimeter() << endl;  // Print perimeter

    return 0;  // Return 0 to indicate successful execution
}

 Output

Area of the circle: 78.5398
Perimeter of the circle: 31.4159

Share this C++ Exercise


More C++ Programming Exercises of Object-Oriented Programming in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.