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 (.).

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.

01 June, 2011

program 51: user defined swap function in C

The need: 
      This is a program to demonstrate the use of pointers in C program. This shows how a pointer solve problem in swapping with user defined function. The swap function implemented here can be used in many bigger programs to swap the values of 2 variables.

The code: 
--------------------------------------------
#include<stdio.h>
void swap(int *a, int *b);
main()
{
  int x=4,y=5;
  printf("values before swap are\n");
  printf("x=%d\ty=%d\n",x,y);
  swap(&x,&y);
  printf("values before swap are\n");
  printf("x=%d\ty=%d\n",x,y);
  return 0;
}
void swap(int *a, int *b)
{
 int tmp;
 tmp=*a;
 *a=*b;
 *b=tmp;
}
--------------------------------------------

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 pass variables by reference in a program. The term "pass by reference" means addresses of variables are passed as arguments to function. Open post55 of this blog and look at the program given there. This program is a cure for the problem encountered there and gives the desired output. How this is done is explained in next para.
    Till now all of us knew that when a function was called it took only values of arguments passed to it. Now here we passed addresses (which are also some values). These values are assigned to other temporary variables in user defined functions. Now look at point 6 of points to remember about pointers section in post55 of this blog. So this temporary variable now points to the variable whose address is passed and can be use to do any operation on it by directly going to that location in memory.The situation is just like the one described in the analogy given below (RP's picture analogy).
    Suppose I have a picture named A located somewhere. I give you a carbon copy of this picture. You have carbon copy now so you know how original picture looks but don't know where the original picture is located. Now I say draw something more on picture. Will you be able to make any changes in original picture A??? The answer is NO. Its obvious that whatever changes you will make will be made only on the carbon copy of that picture which you have. Same is the case when the carbon copy of values is passed to a function. Suppose I also have a paper on which the location of original picture is written so that you can go to the original picture A. I give you carbon copy of the paper which has address written on it and ask you to make same changes in A using carbon copy of address.Will you be able to make any changes in original picture A now??? This time answer is YES. Same is the case when the carbon copy of address is passed to a function.

program 50: using pointers in C

The need: 
      This program was written by me to test the use of pointers in C program. In this program I just declare a pointer, initialized it and used that pointer in some operations.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
  int x,y;
  int *p,*q;
  p=&x;        //p is having address of x
  q=&y;        //q is having address of y
  printf("Enter the values of x and y\n");
  printf("x=");
  scanf("%d",&x);
  printf("y=");
  scanf("%d",&y);
  printf("\nvalue of x is %d\n",*p);
  printf("address of x is %d\n",&x);
  printf("value of p is %d\n\n",p);
  printf("value of y is %d\n",*q);
  printf("address of y is %d\n",&y);
  printf("value of q is %d\n\n",q);
  return 0;
}
--------------------------------------------

The approach: 
Copy, paste, compile and run the program. This is a simple program just to show how pointers can be used in a program. Like pointers p and q are initialized to addresses of variables x and y using &(address operator). This only verifies the concept of address and pointers.
After that these can be used normal variables.
 

Concept of pointers in C

Most of you have heard the term pointer. Those who have not heard, don't worry. All of us are going to know some things about pointers in this post. Through my experience I can say that beginners think pointer to be tough part in C though its not tough but its one of the most important and the most powerful concepts. Let me first give you some examples why pointer was needed:

The need: 

1. Have a look at the program below which was written to exchange the values of 2 variables x and y:
--------------------------------------------
#include<stdio.h>
void swap(int a, int b);
main()
{
  int x=4,y=5;
  printf("values before swap are\n");
  printf("x=%d\ty=%d\n",x,y);
  swap(x,y);
  printf("values before swap are\n");
  printf("x=%d\ty=%d\n",x,y);
  return 0;
}
void swap(int a, int b)
{
 int tmp;
 tmp=a;
 a=b;
 b=tmp;
}
--------------------------------------------
Above program does not give desired output. Check it. The reason behind this is this. When we pass arguments to any function, only the values of argument variables (in our case x and y) are passed and assigned to new variables (in our case a and b) in called function. So when values of a and b are exchanged inside the function, values of x and y remains unchanged. Pointer can handle this problem which will be illustrated later.

2. In normal user defined functions multiple values(like arrays and structures cannot be returned.) For that we have to go to pointers.

Pointer: A pointer(or pointer variable) to any type of variable is a label that contains the address (starting byte address) of that variable in the memory. If a pointer variable p has the address of variable i, technically we say that the pointer p points to the variable x. Type a pointer is the type of the variable pointed. Pointer variables are declared by writing a * before the variable name.ex.
int *p;        //declaration of an integer pointer p


Points to remember about pointers:


Pointers are intended to have only address values so only number of operations on pointers are restricted. Some important points are as under:

1. For now think a pointer to be a normal variable which you will use only to hold addresses.

2. We cannot multiply,divide,add or subtract pointer variables. This is forbidden because the output of these may not be a valid address.

3. We cannot initialize (assign any value to) a pointer directly. This is because pointer can hold address of a valid location in memory. You'll later come to know that pointers can be initialised using dynamic memory allocation.

4. So pointers are initialized by giving address of a valid variable. sample code segment:
int x;         //declaration of an integer x
int *p;        //declaration of an integer pointer p
p=&x;         //initialization of an integer pointer p
after this p holds address of x.
printf("%d",p);
will print the value of address of variable x.

5. Now p can be used to access value of x. This means that the statement:
printf("%d",*p);
will print the value of variable x.

6. 2 pointers can point to same location. This is very obvious if you remember point 1 of this section (2 normal variables can have same values so 2 pointer variables can have same address values).

Additional advantages: 
 Use of pointers is not limited to written above. Everything that uses memory can be pointed by a pointer variable. Arrays, structures and even functions can have pointers pointing to their location because they also reside somewhere in memory. You people may have created text files using notepad or any other text editor. If we want to read or do any operation on text files, we can assign a pointer to point to that file. This is a complete branch of C language called FILE HANDLING in C. Different uses of pointers will be put as more programs are put in the posts.