Topics

6/recent/ticker-posts

Structures Part 2


 Structures in C :



Typedef key word: Typedef is a derived data type. Typedef is a key word to define short cut name or alias name for structure. To derive new data type from existing data type.

 

Its Syntax: Different ways.

1)      1.         struct  Employee 

            {

                        int  empNum; 

                        char empName[30];

                        float salary;

                        char dept[15];

            };

 

2.    struct  Employee  emp1;

            struct  Employee 

            {

                        int  empNum; 

                        char empName[30];

                        float salary;

                        char dept[15];

            };

 

 

typedef struct  Employee  EMPLOYEE;

 

EMPLOYEE  emp1;

typedef struct 

            {

                        int  empNum; 

                        char empName[30];

                        float salary;

                        char dept[15];

            }EMPLOYEE;

 

EMPLOYEE  emp1;

 

Note: typedef key word with pre-defined data types.

 

            typedef   long int LONG;

           

LONG id;

 

Here type of “id”  variable is “long int”

 

Array of structure: It is a collection of similar type of structures;

 

Declaration :

            struct Sample

            {

                        int a;

                        float  b;

                        char  ch;

            };

 

            struct Sample  s[5];

 

Accessing :

 

            s[0].a ;     s[0].b ;        s[0].ch ;

s[1].a ;     s[1].b ;        s[1].ch ;

s[2].a ;     s[2].b ;        s[2].ch ;

s[3].a ;     s[3].b ;        s[3].ch ;

s[4].a ;     s[4].b ;        s[4].ch ;

 

 

 

Program to read and display five employees details.

 

#include<stdio.h>

 

struct Employee

{

   int eno;

   char ename[20];

   float salary;

   char dept[20];

};

int main()

{

            struct Employee  emp[5];

            int i;

            for(i=0; i<5 ; i++)

            {

               printf("\nEnter emp details ");

 

               printf("\nEmp number :");

               scanf("%d",&emp[i].eno);

 

               printf("\nEmp name :");

               scanf("%s",emp[i].ename);

 

               printf("\nEmp salary :");

               scanf("%f",&emp[i].salary);

 

               printf("\nEmp Dept:");

               scanf("%s",emp[i].dept);

            }

 

            printf("\n Num \t Name \t Salary \t Dept ");

            for(i=0; i<5 ; i++)

            {

              printf("\n%d \t %s \t %f \t %s ",emp[i].eno,emp[i].ename,emp[i].salary,emp[i].dept);

            }

getch();

}

 

 

Note: the programs given here are pre compiled and pre runned in Ms DOS Box IDE

Post a Comment

0 Comments