facebook like button

02 June, 2011

program 52: center of mass of a triangle (use of typedef)

The need: 
      This is a program to calculate the center of mass of a triangle. Finding COM is a trivial problem but the program is not trivial because this is the program which tells you how you can define your own data-type in C.

The code: 
--------------------------------------------
#include<stdio.h>
struct p       //defining structure p
{
    float x;
    float y;
};
typedef struct p point;       //defining data-type point

main()
{
    int i;
    point p1,p2,p3,com;      //declaration of point variables
    printf("program to find Center of Mass of a triangle.\n");
    printf("Enter vertices => \n");
    printf("x1 => \t");
    scanf("%f",&p1.x);
    printf("y1 => \t");
    scanf("%f",&p1.y);
    printf("x2 => \t");
    scanf("%f",&p2.x);
    printf("y2 => \t");
    scanf("%f",&p2.y);
    printf("x3 => \t");
    scanf("%f",&p3.x);
    printf("y3 => \t");
    scanf("%f",&p3.y);
    com.x=(p1.x+p2.x+p3.x)/3;
    com.y=(p1.y+p2.y+p3.y)/3;
    printf("\nCOM is (%.2f,%.2f) .\n",com.x,com.y);
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how structures can be used to define a new derived data-type (in our case point is derived data-type which consist of two floats). After data-type point is defined, it can be used to declare  variables in the same way as built-in data-types are used. Else the logic is simpler. You people already know the formula of center of mass of a triangle. Only thing done here is to take input, use the formula to calculate output and print back for user.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply