0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Find Area of Circle with User Input

Use a Bash script that reads the radius and calculates area with area=$(echo "scale=2; 3.1416 * $radius * $radius" | bc) to find the circle's area.
📋

Examples

Input5
OutputArea of circle with radius 5 is 78.54
Input0
OutputArea of circle with radius 0 is 0.00
Input2.5
OutputArea of circle with radius 2.5 is 19.63
🧠

How to Think About It

To find the area of a circle, first get the radius from the user. Then multiply pi (3.1416) by the radius squared. Use a calculator tool like bc in Bash to handle decimal math.
📐

Algorithm

1
Get the radius input from the user
2
Calculate area using formula: pi * radius * radius
3
Print the calculated area with two decimal places
💻

Code

bash
#!/bin/bash
read -p "Enter radius: " radius
area=$(echo "scale=2; 3.1416 * $radius * $radius" | bc)
echo "Area of circle with radius $radius is $area"
Output
Enter radius: 5 Area of circle with radius 5 is 78.54
🔍

Dry Run

Let's trace radius=5 through the code

1

Input radius

User enters 5

2

Calculate area

3.1416 * 5 * 5 = 78.54

3

Print result

Output: Area of circle with radius 5 is 78.54

StepRadiusCalculationArea
153.1416 * 5 * 578.54
💡

Why This Works

Step 1: Reading Input

The script uses read to get the radius from the user.

Step 2: Calculating Area

It uses bc with scale=2 to do decimal math for the formula pi * radius * radius.

Step 3: Displaying Output

Finally, it prints the area with the radius value for clarity.

🔄

Alternative Approaches

Using awk for calculation
bash
#!/bin/bash
read -p "Enter radius: " radius
area=$(awk "BEGIN {printf \"%.2f\", 3.1416 * $radius * $radius}")
echo "Area of circle with radius $radius is $area"
This uses awk instead of bc for floating-point math, which can be faster and simpler on some systems.
Using printf with bash arithmetic (integer only)
bash
#!/bin/bash
read -p "Enter radius (integer): " radius
area=$((3 * radius * radius / 1))
echo "Approximate area (integer) is $area"
This uses integer math only and is less precise but avoids external tools.

Complexity: O(1) time, O(1) space

Time Complexity

The script performs a fixed number of operations regardless of input size, so it runs in constant time.

Space Complexity

It uses a few variables and no extra data structures, so space usage is constant.

Which Approach is Fastest?

Using Bash arithmetic is fastest but limited to integers; awk and bc handle decimals but add slight overhead.

ApproachTimeSpaceBest For
Using bcO(1)O(1)Accurate decimal calculations
Using awkO(1)O(1)Simple decimal math without bc
Bash integer arithmeticO(1)O(1)Fast integer-only calculations
💡
Use bc or awk for decimal math in Bash since Bash can't do floating-point math natively.
⚠️
Trying to do decimal multiplication directly in Bash without bc or awk causes errors or wrong results.