EmbLogic's Blog

C Structure and It’s Simple Programme

1.What is Structure ?
Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person.

2.Keyword struct is used for creating a structure.

3.Syntax of Sructure
struct structure_name
{
data_type vari.1;
data_type vari.2;
.
.
data_type vari.n;
};

4.We Can Create Structure according to above mention example and Formate of Structure

5.

struct person
{
char name[50];
int cit_no;
float salary;
};

6.Structure variable declaration

When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as:

struct person
{
char name[50];
int cit_no;
float salary;
};

Inside main function:
struct person p1, p2, p[20];
when We declare variable then memory allocation done.

Another way of creating sturcture variable is:

struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];

7. Accessing members of a structure

There are two types of operators used for accessing members of a structure.

1. Member operator(.)
2.Structure pointer operator(->) (it is used when variable is Pointer)

Suppose, we want to access salary for variable p2. Then, it can be accessed as:

8. Example of structure

Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet.

/// Header File ////
#include
struct Distance
{
int feet;
float inch;
}

///// C File ///////
#include”header.h”
int main()
{
struct Distance d1,d2,sum;
printf(“1st distance\n”);
printf(“Enter feet: “);
scanf(“%d”,&d1.feet); /* input of feet for structure variable d1 */
printf(“Enter inch: “);
scanf(“%f”,&d1.inch); /* input of inch for structure variable d1 */
printf(“2nd distance\n”);
printf(“Enter feet: “);
scanf(“%d”,&d2.feet); /* input of feet for structure variable d2 */
printf(“Enter inch: “);
scanf(“%f”,&d2.inch); /* input of inch for structure variable d2 */
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if (sum.inch>12)
{
++sum.feet;
sum.inch=sum.inch-12;
} //If inch is greater than 12, changing it to feet.

printf(“Sum of distances=%d\’-%.1f\””,sum.feet,sum.inch);
/* printing sum of distance d1 and d2 */
return 0;
}

9.OUTPUT

1st distance
Enter feet: 10
Enter inch: 4.5
2nd distance
Enter feet: 4
Enter inch: 10.5
Sum of distances= 15′-3″

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>