Saturday 9 December 2017

Structure Example

Q : What is meant by structure data type? How do we reference the elements of a structure?
Give example of how a value of a structure can be assigned to another structure.

Solution : 


A structure is user defined data type which is used to store record based data. Structure is useful when there is a need to process record type data for example student record which is a combination of more than variable (roll,name,class,marks etc). Structure encapsulates more than one variable into a single logical unit. Without structure, processing of record based data is not an easy task. Programmer need to declare many variables with different name. Which increase complexity?



Structure minimize programmer task for handling record base data. You need to make a single variable which will hold many data into a single unit. Data setting totally depend up to user. Array of structure is also useful to process more than record.

Syntax for define a structure


struct <structure_name>
{
    data_type  Var_Name1;
   data_type   Var_Name2;
   .
   .
   .
   data_type Var_NameN;

}

Dot (.) Operator
Dot (.) operator is use to access structure member for read and write.
Example :

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

struct stu
{
     int roll;
     char name[10];
     float marks;
};
void main()
{
     struct stu ob;
     clrscr();
     printf("Enter Roll>> ");
     scanf("%d",&ob.roll);
     fflush(stdin);
     printf("Enter Name>> ");
     gets(ob.name);
     printf("Enter Marks>> ");
     scanf("%f",&ob.marks);
     printf("\nPrinting Data\n");
     printf("\n\tRoll=%d",ob.roll);
     printf("\n\tName=%s",ob.name);
     printf("\n\tMarks=%.2f",ob.marks);
     getch();

}

Assigned a structure into other structure


struct stu
{
     int roll;
     float mark1;
     float mark2;
};
void main()
{
     struct stu ob1={101,12.23,45.45},ob2;
     clrscr();
     ob2=ob1;
     printf("\n\tRoll=%d,\tMark1=%.2f,\tMark=%.2f",ob2.roll,ob2.mark1,ob2.mark2);
     getch();

}

                             Download PDF
                           Download Source Code

No comments:

Post a Comment