C Programming Language


Why need of the Structure in C ?

Suppose, You need information about each horse such as its name, its date of birth, its coloring, its height, its parentage, and so on. Some items are strings and some are numeric. Clearly, you could set up arrays for each type of data and store them quite easily.


Structure :

The struct keyword enables you to define a collection of variables of various types called a structure that you can treat as a single unit.


Defining Structure Types and Structure Variables :

A variable of any type can be a member of a structure, including arrays. There are five members to this version of the Horse structure type: the integer members age and height, and the arrays of char elements, name, father, and mother.
         Each struct member declaration is essentially the same as a normal variable declaration, with the type followed by the name and terminated by a semicolon.


Accessing Structure Members :

A structure variable name is not a pointer. You need a special syntax to access the members.
You refer to a member of a structure by writing the variable name followed by a period, followed by the member variable name.

For example, if you found that dobbin had lied about his age and was actually much younger than the initializing value would suggest, you could amend the value by writing this:

dobbin.age = 12;

Also you can define as :

Horse trigger = {
     .height = 15, .age = 30, .name = "Trigger", .mother = "Wesson", .father = "Smith"


Example :

Output :

Enter the name of the horse: Neddy
How old is Neddy? 12
How high is Neddy ( in hands )? 14
Who is Neddy's father? Bertie
Who is Neddy's mother? Nellie

Neddy is 12 years old, 14 hands high, and has Bertie and Nellie as parents.