Problem Statement: Given the radius of the circle, calculate the area of the circle.
Examples:
Example 1: Input: N = 5 Output: 78.5 Explanation: Using formula πr2 for finding area of circle we get area as 78.5 Example 2: Input: N = 4 Output: 50.2 Explanation: Using formula πr2 for finding area of circle we get area as 50.2
Solution
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Approach:
- We know that the area of the circle is πr2.
- So taking a variable double to store decimal digits as our ans.
- And multiplying pi with the square of the radius gives us the area of the circle.
Code:
C++ Code
#include <bits/stdc++.h>
using namespace std;
class Area {
public:
void areaOfCircle(int n) {
double ans = 3.14 * n * n; // Area of circle = πr2
cout << "Area of circle is : ";
cout << ans;
}
};
int main() {
int n = 5;
Area p1;
p1.areaOfCircle(n);
return 0;
}
Output:
Area of circle is: 78.5
Time Complexity: O(1)
Space Complexity: O(1)
Java Code
class Solution {
public static void areaOfCircle(int n) {
double ans = 3.14 * n * n; // Area of circle = πr2
System.out.print("Area of circle is : " + ans);
}
public static void main(String args[]) {
int n = 5;
areaOfCircle(n);
}
}
Output:
Area of circle is: 78.5
Time Complexity: O(1)
Space Complexity: O(1)
Special thanks to Rushikesh Adhav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article