facebook like button

03 June, 2011

program 53: center of mass of a triangle (user defined function)

The need: 
      This is a program to calculate the center of mass of a triangle. This is same previous program with only difference of user defined function. This program shows how a structure can be returned by a function by using pointers.

The code: 
--------------------------------------------
#include<stdio.h>
struct p       //defining structure p
{
    float x;
    float y;
};
typedef struct p point;       //defining data-type point
point * com_tri(point a,point b,point c);
main()
{
    int i;
    point p1,p2,p3;      //declaration of point variables
    point *com;         //declaration of pointer com of type point
    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=com_tri(p1,p2,p3);
    printf("\nCOM is (%.2f,%.2f) .\n",com->x,com->y);
}
point * com_tri(point a,point b,point c)
{
    point temp_com;
    temp_com.x=(a.x+b.x+c.x)/3;
    temp_com.y=(a.y+b.y+c.y)/3;
    return(&temp_com);        //address of temp_com is returned
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how pointers can be used to return a struct data-type (in our case point is derived data-type which consist of two floats). Here com_tri is a function which is defined to take 3 arguments of type point and return a pointer of type point. If you see the definition of function, you'll see that the function declares a point variable in which the calculated values of COM is stored. This variable is stored somewhere in the memory. In the end program returns the address of variable this variable. When in main program this function is called, this returns that address to a pointer variable com. Now there is one noticeable point here. Which is accessing of individual components of pointer variable com. When we access individual components of a structure from its pointer, we use an arrow (->) as separator in place of a dot (.).

No comments:

Post a Comment

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