C Online Compiler
Example: Area Calculator using Functions in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Area Calculator using Functions #include <stdio.h> // For printf, scanf #include <math.h> // For M_PI (pi constant) // Function to calculate the area of a circle // Parameters: radius (float) // Returns: area of the circle (float) float areaCircle(float radius) { return M_PI * radius * radius; } // Function to calculate the area of a square // Parameters: side (float) // Returns: area of the square (float) float areaSquare(float side) { return side * side; } // Function to calculate the area of a rectangle // Parameters: length (float), width (float) // Returns: area of the rectangle (float) float areaRectangle(float length, float width) { return length * width; } int main() { int choice; float radius, side, length, width; float resultArea; // Step 1: Display menu to the user printf("Enter the shape for which to calculate area:\n"); printf("1. Circle\n"); printf("2. Square\n"); printf("3. Rectangle\n"); printf("Enter your choice (1-3): "); scanf("%d", &choice); // Step 2: Process user's choice using a switch statement switch (choice) { case 1: printf("Enter the radius of the circle: "); scanf("%f", &radius); resultArea = areaCircle(radius); // Call the areaCircle function printf("Area of the circle with radius %.2f is: %.2f\n", radius, resultArea); break; case 2: printf("Enter the side length of the square: "); scanf("%f", &side); resultArea = areaSquare(side); // Call the areaSquare function printf("Area of the square with side %.2f is: %.2f\n", side, resultArea); break; case 3: printf("Enter the length of the rectangle: "); printf("Enter the width of the rectangle: "); scanf("%f", &length); scanf("%f", &width); resultArea = areaRectangle(length, width); // Call the areaRectangle function printf("Area of the rectangle with length %.2f and width %.2f is: %.2f\n", length, width, resultArea); break; default: printf("Invalid choice. Please enter a number between 1 and 3.\n"); break; } return 0; }
Output
Clear
ADVERTISEMENTS