Friday, 7 April 2017

Understanding structure In c programming

Understanding structure In C programming: - Which workman is adequate who knows how to repair just a single kind of vehicle? None. The Same thing is valid about C dialect. It wouldn't have been so famous had it been ready to deal with just all ints, or all boys or all scorches at once. In certainty when we handle genuine information, we don't ordinarily manage little particles of data without anyone else—things like whole numbers, characters and such. Rather we manage elements that are accumulations of things, everything having its own traits, similarly as the substance we call a "book" is a gathering of things, for example, title, creator, call number, distributor, the number of pages, date of production, and so on. As should be obvious this information is divergent, for case creator is a string, while the number of pages is a whole number. For managing such accumulations, C gives an information sort called 'structure'. A structure assembles, distinctive particles of data that involve a given element. What's more, a structure is the point of this section.

What is structure and why we use it?

What is structure?

A structure is a client characterized information sort in C which permits you to join diverse information sorts to store a specific kind of record. Structure builds a perplexing information sort in the more significant way. It is fairly like an Array. The main contrast is that exhibit is utilized to store the accumulation of comparative datatypes while structure can store gathering of an information. 

The structure is utilized to speak to a record. Assume you need to store the record of Student which comprises of understudy name, address, move number and age. You can characterize a structure to hold this data.


Why we use it?

We have seen before how ordinary variables can hold one bit of data and how arrays can hold various bits of data of similar information sort. These two data type types handle an incredible assortment of circumstances. Be that as it may, frequently we manage elements that are gathering of divergent data types.
For instance, assume you need to store information about a book. You might need to store its name (a string), its value (a float) and a number of pages in it (an int). On the off chance that information about say 3 such books is to be put away, then we can take after two methodologies:

1 Develop individual arrays, one for putting away names, another for putting away costs and still another for putting away various pages. 

2 Utilize a structure variable. Give us a chance to analyze these two methodologies one by one. For programming, accommodation expects that the names of books would be single character long. Give us a chance to start with a program that employments arrays.


structure In c programming example

main( )
{
char name[3] ;
float price[3] ;
int pages[3], i ;
printf ( "\nEnter names, prices and no. of pages of 3 books\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
scanf ( "%c %f %d", &name[i], &price[i], &pages[i] );
printf ( "\nAnd this is what you entered\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "%c %f %d\n", name[i], price[i], pages[i] );
}

And here is the result.

Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512
And this is what you entered
A 100.000000 354
C 256.500000 682
F 233.700000 512

This approach doubtlessly permits you to store names, costs, and a number of pages. Be that as it may, as you more likely than not understood, it is a clumsy approach that clouds the way that you are managing a gathering of qualities identified with a solitary substance—the book.

The program turns out to be harder to deal with as the quantity of thing identifying with the book continues expanding. For instance, we would be required to utilize various exhibits, on the off chance that we additionally choose to store a name of the distributor, date of procurement of book, and so forth. To settle this issue, C gives a unique information sort—the structure. A structure contains various information sorts gathered together. These information sorts might possibly be of a similar sort. The taking after case delineates the utilization of this information sort.

main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ;
scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
printf ( "\nAnd this is what you entered" ) ;
printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;
printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;
printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ;
}

And here is the output...

Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512

And this is what you entered
A 100.000000 354
C 256.500000 682
F 233.700000 512

This program shows two central parts of structures: 

(a) declaration of a structure 

(b) getting to of structure components 

Give us now a chance to take a gander at these ideas one by one

Declaring a Structure in c programming

In our example program, the following statement declares the
structure type in c programming:

struct book
{
char name ;
float price ;
int pages ;
} ;

This announcement characterizes another information sort called struct book. Each variable of this information sort will comprise of a character variable called name, a float variable called cost and an integer variable called pages. The general type of a structure affirmation explanation is given beneath:

struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
} ;

Once the new structure information sort has been characterized at least one factors can be proclaimed to be of that sort. For instance, the factors b1, b2, b3 can be proclaimed to be the sort struct book, as,

struct book b1, b2, b3 ;

This announcement puts aside space in memory. It makes accessible space to hold every one of the components in the structure—for this situation, 7 bytes—one for a name, four for cost and two for pages. These bytes are dependably in neighboring memory areas.
If we so desire, we can combine the declaration of the structure type and the structure variables in one statement.

For example,
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
is same as...
struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
or even...
struct
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

Like essential factors and arrays, structure factors can likewise be introduced where they are announced. The organization utilized is very like that used to start arrays.

struct book
{
char name[10] ;
float price ;
int pages ;
} ;
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;

Take note of the accompanying focuses while declaring a structure type:

1 The end prop in the structure sort assertion must be taken after by a semicolon. 

2 Understand that a structure sort assertion does not advise the compiler to save any space in memory. All a structure presentation does is, it characterizes the "shape" of the structure. 

3 Generally, structure sort statement shows up at the highest point of the source code document before any factors or capacities are characterized. In extensive projects, they are normally placed in a different header document and the record is incorporated (utilizing the preprocessor mandate #include) in whichever program we need to utilize this structure sort.

Accessing Structure Elements

Having pronounced the structure sort and the structure factors, let we perceive how the components of the structure can be gotten to. In arrays, we can get to individual components of an array utilizing a subscript. Structures utilize an alternate plan. They utilize a speck (.) administrator. So to allude to pages of the structure characterized, in our test program we need to utilize,

b1.pages
Similarly, to refer to price we would use,
b1.price
Note that before the dot there must always be a structure variable
and after the dot, there must always be a structure element.

How Structure Elements are Stored

Whatever be the components of a structure, they have constantly put away in touching memory areas. The accompanying system would represent this:

/* Memory map of structure elements */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
printf ( "\nAddress of price = %u", &b1.price ) ;
printf ( "\nAddress of pages = %u", &b1.pages ) ;
}

Here is the output of the program...
Address of name = 65518
Address of price = 65519
Address of pages = 65523

Array of Structures

Our specimen program indicating utilization of structure is somewhat basic disapproved. Everything it does is, it gets values into different structure components and yield these qualities. In any case, that is all we planned to do anyway... demonstrate how structure sorts are made, how structure factors are pronounced and how singular components of a structure variable are referenced. 

In our example program, to store information of 100 books we would be required to utilize 100 diverse structure factors from b1 to b100, which is unquestionably not extremely helpful. A superior approach would be to utilize a variety of structures. Taking after program demonstrates to utilize a variety of structures

/* Usage of an array of structures */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b[100] ;
int i ;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "\nEnter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}
for ( i = 0 ; i <= 99 ; i++ )
printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
}
linkfloat( )
{
float a = 0, *b ;
b = &a ; /* cause emulator to be linked */
a = *b ; /* suppress the warning - variable not used */
}

Now few thing about the program

1 See how the variety of structures is proclaimed... 
struct book b[100] ; 
This gives space in memory to 100 structures of the sort struct book.

2 The language structure we use to reference every component of the array b is like the punctuation utilized for arrays of ints and roasts. For illustration, we allude to zeroth book's cost as b[0].price. Likewise, we allude first book's pages as b[1].pages.

It ought to be acknowledged what watchful thought Dennis Ritchie has put into C dialect. He initially characterized cluster as a gathering of comparable components; then understood that disparate information sorts that are frequently found, all things considered, can't be dealt with utilizing clusters, in this manner made another information sort called structure. In any case notwithstanding utilizing structures programming accommodation couldn't be accomplished, in light of the fact that a considerable measure of factors (b1 to b100 for putting away  information around hundred books) should have been taken care of. In this manner he permitted us to make a variety of structures; a variety of comparable information sorts which themselves are an accumulation of disparate information sorts. Caps off to the virtuoso!

In an array of structures, all components of the array are put away in neighboring memory areas. Since every component of this array is a structure, and since all structure components are constantly put away in neighboring areas, you can picture the game plan of an array of structures in memory. In our illustration, b[0]'s name,, cost and pages in memory would be quickly taken after by b[1]'s name,, cost and pages, and so on.

What is the capacity linkfloat( ) doing here? In the event that you don't characterize it you will undoubtedly get the blunder "Coasting Point Designs Not Linked" with dominant part of C Compilers. What makes this mistake happen? While parsing our source record, if the compiler experiences a reference to the address of a float, it sets a banner to have the linker connect in the floating point emulator. A floating point emulator is utilized to control floating point numbers in runtime library functions like scanf( ) and atof( ). There are a few cases in which the reference to the float is somewhat dark and the compiler does not distinguish the requirement for the emulator. The most widely recognized are utilizing scanf( ) to peruse a float in an array of structures as appeared in our program. 

How might we constrain the arrangements to be connected? That is the place the linkfloat( ) work comes in. It powers connecting of the coasting point emulator into an application. There is no need to call this capacity, simply characterize it anyplace in your program.

Uses Of Structure

Where are structures valuable? The prompt application that strikes a chord is Database Management. That is, to keep up information about representatives in an association, books in a library, things in a store, budgetary bookkeeping exchanges in an organization and so on. In any case mind you, utilization of structures extends much past database administration. They can be utilized for an assortment of purposes like:
  • Changing the extent of the cursor 
  • Clearing the substance of the screen 
  • Putting the cursor at a fitting position on screen 
  • Drawing any illustrations shape or graphics shape on the screen 
  • Getting a key from the console 
  • Checking the memory size of the PC 
  • Discovering the rundown of hardware joined to the PC 
  • Designing a floppy 
  • Concealing a record from the registry 
  • Showing the registry of a circle 
  • Sending the yield to printer 
  • Associating with the mouse

Conclusion

  1. A structure is normally utilized when we wish to store disparate information together. 
  2. Structure components can be gotten to through a structure variable utilizing a speck (.) administrator. 
  3. Structure components can be gotten to through a pointer to a structure utilizing the bolt (- >) administrator. 
  4. All components of one structure variable can be allotted to another structure variable utilizing the task (=) administrator. 
  5. It is conceivable to pass a structure variable to a capacity either by esteem or by address. 
  6. It is conceivable to make a variety of structures.

Some example of structure

How to calculate difference between  two time periods


#include <stdio.h>
struct TIME
{
  int seconds;
  int minutes;
  int hours;
};
void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct TIME *diff);

int main()
{
    struct TIME startTime, stopTime, diff;

    printf("Enter start time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds);

    printf("Enter stop time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d %d %d", &stopTime.hours, &stopTime.minutes, &stopTime.seconds);

  
    differenceBetweenTimePeriod(startTime, stopTime, &diff);

    printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours, startTime.minutes, startTime.seconds);
    printf("%d:%d:%d ", stopTime.hours, stopTime.minutes, stopTime.seconds);
    printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);

    return 0;
}

void differenceBetweenTimePeriod(struct TIME start, struct TIME stop, struct TIME *diff)
{
    if(stop.seconds > start.seconds){
        --start.minutes;
        start.seconds += 60;
    }

    diff->seconds = start.seconds - stop.seconds;
    if(stop.minutes > start.minutes){
        --start.hours;
        start.minutes += 60;
    }

    diff->minutes = start.minutes - stop.minutes;
    diff->hours = start.hours - stop.hours;
}


Let see another example of structure

#include <stdio.h>  
#include <string.h>  
struct employee    
{   int id;    
    char name[50];    
    float salary;    
}e1,e2;  
int main( )  
{  
   e1.id=101;  
   strcpy(e1.name, "Suraj tiwari"); 
   e1.salary=56000;  

   e2.id=102;  
   strcpy(e2.name, "rahul thakur");  
   e2.salary=126000;  
   
   printf( "employee 1 id : %d\n", e1.id);  
   printf( "employee 1 name : %s\n", e1.name);  
   printf( "employee 1 salary : %f\n", e1.salary);  
  
   printf( "employee 2 id : %d\n", e2.id);  
   printf( "employee 2 name : %s\n", e2.name);  
   printf( "employee 2 salary : %f\n", e2.salary);  
  
   return 0;