Thursday, February 23, 2012

Structures & Union.



Structures & Union


Structures are a form of storage like arrays. The difference between an array and a structure is in an array all components are of the same type where in a structure you can have different types of data. In general an object may need a variety of data types, for example to keep record of a student's marks we need - name, roll no, marks etc. To store these set of data under  a single variable name as Student and it is possible to access all these parameters under one name as student.  All these can be achieved by using a data type called a Structure.  A Structure is a group of one or more variables, usually of various types, and identified by a single name.

Declare a Structure

To declare a structure one has to first define the contents of the structure.  This will then be used as a template to declare variables of that particular structure. 

struct student
{  char name[20] ;
    int roll,eng,science,maths;
} stud;

Here, student is the name of the structure, also known as structure tag and stud is structure label or structure variable. A structure label can be created later by using structure name, like this struct student stud;

To access elements in a structure, a record selector (.) is use.

To declare additional variables of the same type, use of the keyword "struct" followed by the <struct type name>, followed by the variable names.

Structures can contain other structures as members, it is known as nested structure.
                  
Example :

 struct date_of_birth {
 int dd,mm,yy;
  };
 
 struct personal {
 char name[20],address[30];
 struct date_of_birth  dob;
  };

Arrays of structures

The arrays of basic types such as integers and floats are allowed in C, so are arrays of structures. An array of structures is declared in the usual way:

struct student
{  char name[20] ;
    int roll,eng,science,maths;
} stud[5];


Using typedef we can create an "alias" types from structure label(variable).

Example:
typedef struct
{  char name[20] ;
    int roll,eng,science,maths;
} student;

student stud;


Union

Unions are declared in the same fashion as structs, but have a fundamental difference. Only one item within the union can be used at any time, because the memory allocated for each item inside the union is in a shared memory location.

union student
{  char name[20] ;
    int roll,eng,science,maths;
} stud;


Different Between Array and Structure

Array

Structure
  1. In an array all components are of the same type.
  2. In an array the components are identified by a number as in table[37].
  3. An array we declare the array for each variable.

  1. In a structure you can have different types.
  2. A structure we refer to the individual components by name.
  3. In structure we declare a Structure first then use our structure declaration as a new type and declare variables of this type.



Different Between Structure and Union

Structure

Union
  1. Structure is a combination elements, which can be predefined data types or other structure. The length/size of the structure is the sum of the length of its elements.
  2. A structure allocates the memory equal to the total memory required by the members.
  3.  structure, each member have their own memory space.

  1. Union is a combination elements, which can be predefined data types or other union . But, the size/length of union is the maximum of internal elements.
  2. union allocates the memory equal to the maximum memory required by the member of the union. 
  3. In union, one block is used by all the member of the union.


Example of Union

#include <stdio.h>
#include <conio.h>

void main()
      {
           union books
              {
                   char bname[20],author[20];
                   int nc;
              }book;
           clrscr();
           printf("\nEnter Book Name... ");
           gets(book.bname);
           printf("\nName :  %s ",book.bname);
           printf("\nEnter Author Name... " );
           gets(book.author);
           printf("\nAuthor Name :\n",book.author);
           printf("\nEnter the no. copies...");
           scanf("%d",&book.nc);
           printf("\nNo. of Copies : %d\n",book.nc);
           getch();
      }

Example of Simple Structure

#include <stdio.h>
#include <conio.h>

void main()
      {
           struct books
              {
                   char bname[20],author[20];
                   int nc;
              }book;
           clrscr();
           printf("\nEnter Book Name... ");
           gets(book.bname);
           printf("\nEnter Author Name... " );
           gets(book.author);
           printf("\nEnter the no. copies...");
           scanf("%d",&book.nc);
           printf("\nAuthor Name :\n",book.author);
           printf("\nName :  %s ",book.bname);
           printf("\nNo. of Copies : %d\n",book.nc);
           getch();
      }

Example of Array / Nested Structure

#include <stdio.h>
#include <conio.h>

void main()
      {
           struct date
              {
                   int dd,mm,yy;
              };
           struct emp
              {
                   int ecode;
                   char name[20];
                   struct date jd;
                   float sal;
              }em[10];
           int i,n;
           float s;
           clrscr();
           printf("\n\tEnter Nos. of Employee [below 10] : ");
           scanf("%d",&n);
           for(i=0;i<n;i++)
              {
                   printf("\n\tEnter Employee Code : ");
                   scanf("%d",&em[i].ecode);
                   printf("\n\tEnter Employee Name : ");
                   fflush(stdin);
                   gets(em[i].name);
                   fflush(stdin);
                   printf("\n\tEnter Employee Date of Birth : ");
                   printf("\n\t\tEnter Day : ");
                   scanf("%d",&em[i].jd.dd);
                   printf("\n\t\tEnter Month : ");
                   scanf("%d",&em[i].jd.mm);
                   printf("\n\t\tEnter Year : ");
                   scanf("%d",&em[i].jd.yy);
                   printf("\n\tEnter Employee Salary : ");
                   scanf("%f",&s);
                   em[i].sal=s;
              }
           printf("\n\n\t The data \n");
           printf("\n------------------------------------------------------------");
           printf("\n  Code    Name                   Date of Join       Salary");
           printf("\n------------------------------------------------------------");
           for(i=0;i<n;i++)
              {
                   printf("\n  %d\t  %-20s\t%2d-%2d-%4d\t%8.2f",em[i].ecode,em[i].name,em[i].jd.dd,em[i].jd.mm,em[i].jd.yy,em[i].sal);
              }
           printf("\n------------------------------------------------------------");
           getch();
      }

Sorting with Array Structure

#include <stdio.h>
#include <conio.h>

  struct report
       {
           char name[20];
           int marks;
      }    rep[3],temp;

  void disp()
      {
           int i;
           for(i=0;i<3;i++)
              {
                   printf("\nName :  %s   Marks  : %d",rep[i].name,rep[i].marks);
              }
      }

  void main()
      {
           int i,j;
           clrscr();
           for(i=0;i<3;i++)
              {
                   printf("\nEnter Name : ");
                   fflush(stdin);
                   gets(rep[i].name);
                   printf("\nEnter Total Marks : ");
                   scanf("%d",&rep[i].marks);
               }
           printf("\nOriginal \n");
           disp();
           for(i=0;i<3;i++)
              {
                   for(j=0;j<3;j++)
                        {
                            if(rep[i].marks>rep[j].marks)
                                {
                                      temp=rep[i];
                                      rep[i]=rep[j];
                                      rep[j]=temp;
                                }
                        }
              }
           printf("\n\nSorted in Dscending Order\n");
           disp();
           getch();
      }


Thursday, February 16, 2012

Pointer in C - A Brief Explanation.



A Pointer in C is a special kind of variable which can store address of another variable. ‘C’ is not an object oriented programming so creating objects are not allowed but use of pointer and function pointer allow C to be used in a more object orientated way; C doesn't support objects, but a structure can contain a collection of data and function pointers so the structure can effectively contain data and the functions needed to process it. A Pointer declare with ‘*’ and the unary operator `&' is used to produce the address of an object.

Reference operator (&)
When we declare a variable the amount of memory needed is assigned for it at a specific location in memory. To know the exact location of the variable we use & operator.

Dereference operator (*)
A variable which stores a reference to another variable is called a pointer. Pointer variable should be declare using deference operator.

Pointer Arithmetic’s
We can perform addition and subtraction operations with pointers. By addition and subtraction pointers move according to the size of the data type size occupied in the memory for which the said pointer is pointing.

int x, *p;
p = &x;   //Address of integer variable a stored to a Pointer *p

String with pointer.

       char *ch;
       char ch1[50];  
       ch = &ch1[0];    //Address of ‘0’ location stored to a Pointer character *ch.

Pointer and Array
int a[10],*p;
p=&a[0];

Function Pointer

Function Pointers are pointers type variables, which point to the address of a function.  The executable compiled program code and the used variables, are put inside this memory.

Example

#include <stdio.h>
#include <conio.h>

   void main()
      {
           int a,*a1,b;
           clrscr();
           a=20;
           b=a;
           a1=&a;
           printf("  a = %d   &a = %u   a1  = %u a1 = %d  b = %d \n",a,&a,a1,*a1,b);
           a=a+5;
           printf("  a = %d   &a = %u   a1  = %u  a1 = %d  b = %d ",a,&a,a1,*a1,b);
           getch();
      }
Here address of variable ‘a’ is assigned t pointer ‘p’ and value stored to a variable ‘b’.

output  –

  a = 20   &a = 65524   a1  = 65524 a1 = 20  b = 20
  a = 25   &a = 65524   a1  = 65524  a1 = 25  b = 20

Output are the values of variable ‘a’ and the address of ‘a’ but in second case value of a change and variable ‘b’ is unchaged  but the pointer ‘a1’ that pointing to the variable ‘a’ is changes.

Pointers pointing to another Pointer

#include <stdio.h>
#include <conio.h>

      void main()
           {
              int a,*i,**j,***k;
              clrscr();
              a=10;
              i=&a;
              j=&i;
              k=&j;
              printf(" a = %d  i = %u  j = %u    k = %u ",a,i,j,k);
              printf(" a = %d  i = %d  j = %d    k = %d ",a,*i,**j,***k);
              getch();
           }
Output -
       a = 10  i = 65524  j = 65522    k = 65520
       a = 10  i = 10  j = 10    k = 10

Pointer and String. Printing each character and counting the string length.

#include <stdio.h>
#include <conio.h>
  void main()
      {
           char *s="bay of bengal";
           int n;
           clrscr();
           for(n=0; *s != '\0'; s++ )
              {
                   printf("   %c\n ",*s);
                   n++;
              }
           printf(" Nos of character  %d",n);
           getch();
      }

Output -

   b
   a
   y

   o
   f

   b
   e
   n
   g
   a
   l
 Nos of character  13


Pointer and Array

#include <stdio.h>
#include <conio.h>

  void main()
      {
           int arr[]={5,3,9,12}, *ptr;
           clrscr();
           ptr=&arr[0];
           printf("\n\tOutput – ")
           while(*ptr)
              {
                   printf("%d ",*ptr);
                   ptr++;
              }
           getch();
      }


         Output -  5 3 9 12


Thursday, February 9, 2012

Array [XVII] - 2-D Array – Spiral Matrix



Spiral Matrix or Circular Matrix - Produce a spiral array. A spiral array is a square arrangement of the first N2 natural numbers, where the numbers increase sequentially as you go around the edges of the array spiralling inwards.



#include <stdio.h>
#include <conio.h>

  void main()
   {
      int ar[10][10];
      int i,j,r=0,n,size,c=0;
      clrscr();
      printf("\n\tEnter Size  : ");
      scanf("%d",&n);
      for(i=0;i<n;i++)
           {
              for(j=0;j<n;j++)
                   {

                        ar[i][j]=0;
                   }
           }
      size=n;
      i=1;

      while(i<=size*size)
           {
              for(j=0;j<n;j++)
                   {
                        ar[r][c++]=i++;
                   }
              r++;
              c--;
              if(i<=size*size)
                   {
                        for(j=0;j<n-1;j++)
                            {
                                ar[r++][c]=i++;
                            }
                        r--;
                        c--;
                   }
              if(i<=size*size)
                   {
                        for(j=0;j<n-1;j++)
                            {
                                ar[r][c--]=i++;
                            }
                        r--;
                        c++;
                   }
              if(i<=size*size)
                   {
                        for(j=0;j<n-2;j++)
                            {
                                ar[r--][c]=i++;
                            }
                        r++;
                        c++;
                   }
              n=n-2;
           }

      printf("\n\tThe array->\n");
      for(i=0;i<size;i++)
           {
              printf("\n\t");
              for(j=0;j<size;j++)
                   {
                        printf("%3d ",ar[i][j]);
                   }
           }

      getch();
  }

Spiral Matrix - Inbound

#include <stdio.h>
#include <conio.h>

 void main()
   {
      int ar[10][10];
      int i,j,r=0,n,size,c=0;
      clrscr();
      printf("\n\tEnter Size  : ");
      scanf("%d",&n);
      for(i=0;i<n;i++)
           {
              for(j=0;j<n;j++)
                   {

                        ar[i][j]=0;
                   }
           }
      size=n;
      i=size*size;
      c=r=size-1;

      while(i>=1)
           {
              for(j=0;j<n;j++)
                   {
                        ar[r--][c]=i--;
                   }
              r++;
              c--;
              if(i>=1)
                   {
                        for(j=0;j<n-1;j++)
                            {
                                ar[r][c--]=i--;
                            }
                        r++;
                        c++;
                   }
              if(i>=1)
                   {
                        for(j=0;j<n-1;j++)
                            {
                                ar[r++][c]=i--;
                            }
                        r--;
                        c++;
                   }
              if(i>=1)
                   {
                        for(j=0;j<n-2;j++)
                            {
                                ar[r][c++]=i--;
                            }
                        r--;
                        c--;
                   }
              n=n-2;
           }

      printf("\n\tThe array->\n");
      for(i=0;i<size;i++)
           {
              printf("\n\t");
              for(j=0;j<size;j++)
                   {
                        printf("%3d ",ar[i][j]);
                   }
           }

      getch();
  }