Home > Enterprise >  Find the area of a circle using C language
Find the area of a circle using C language

Time:01-02

I am a beginner to coding.I have to find the area of a circle using c ,I wrote the code but when I run it ,it shows 'undefined reference to main'.Please explain what I'm doing wrong

What I have tried:

#include <stdio.h>

float area(float r)
{
    float area;
    
    printf("\nEnter the radius of Circle : ");
    scanf("%f", &r);
    area = 3.14 * r * r;
    printf("\nArea of Circle : %f", area);

    
    return area;

}

CodePudding user response:

Every hosted C program has a primary function that must be named main. The main function serves as the starting point for program execution.

This program first reads the radius of the circle from the user, then calculates the area using the formula area = pi * radius^2. Finally, it prints the result.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void) {
  double radius;
  double area;

  // Read the radius of the circle from the user.
  printf("Enter the radius of the circle: ");
  if(scanf("%lf", &radius) != 1) // If user enter invalid stuff…
  {
    fprintf(stderr, "Error: invalid input.\n");
    return EXIT_FAILURE; // EXIT_FAILURE means error.
  }

  // Calculate the area of the circle
  area = M_PI * radius * radius;

  // Print the result
  printf("The area of the circle is: %f.\n", area);

  return EXIT_SUCCESS; // EXIT_SUCCESS means success.
}

CodePudding user response:

Instead of hard coding the magic value 3.14 use a constant. On my host math.h defines M_PI if __USE_OPEN, __USE_MISC or __USE_GNU are defined. If your math.h doesn't you can define it like this:

#ifndef M_PI
#    define M_PI 3.14159265358979323846
#endif

The entry point for a hosted c program is the function int main() (or int main(int, char *[]). This is your main problem.

area() takes a float r argument, but you populate that variable in in the function itself. Either leave out the argument or as shown here let caller do the I/O and pass in the argument and return the result.

Always check the return value of scanf() otherwise you may be operating on uninitialized values.

Prefer trailing to leading \n as the output stream might be line buffered.

#define __USE_XOPEN
#include <math.h>
#include <stdio.h>

float area(float r) {
    return M_PI * r * r;
}

int main() {
    printf("Enter the radius of Circle : ");
    float r;
    if(scanf("%f", &r) != 1) {
         printf("scanf failed\n");
         return 1;
    }
    printf("Area of Circle : %f\n", area(r));
}
  •  Tags:  
  • c
  • Related