< Prev
Next >



C - Structure with array




As we have know that by using structure, C allow us to create a data type, which can be a collection of different primitive data type elements such as int, char, float, double etc. But, do you also know that you could even have an array as an element of structure? Yes, it is possible. Let's understand the need of having an array as a element of structure by an example.


Let's suppose, we have to store a collection of information about a employee, such as -
In such situation, we would have to use structure to create a data type which can be a collection not just primitive data types but also an array element. Let's understand such structure with an example.




  • Understanding structure with an array element by an example


  • In this example, we have created a structure named employee which has three elements of different type, such as -

    /* An example of structure with array element */
    
    #include<stdio.h>
    
    int main()
    {
    
    /* Declaring a structure */
    struct employee
    {
    	char name[20];
    	int age;
    	float salary;
    };
    
    /* Declaring a structure variable */
    struct employee e1;
    
    printf("Enter the name of employee : ");
    gets(e1.name);	/* using gets() function to read a multi-word string from console */
    
    printf("Enter the age of employee :");
    scanf("%d", &e1.age);
    
    printf("Enter the salary of the first employee : ");
    scanf("%f", &e1.salary);
    
    
    printf("The name of first employee : %s", e1.name);
    printf("\n");
    
    printf("The age of first employee : %d", e1.age);
    printf("\n");
    
    printf("The salary of first employee : %.2f", e1.salary);
    
    return 0;
    }
    
    



    Output is :

    Enter the name of employee : First Employee
    Enter the age of employee :24
    Enter the salary of the first employee : 10000
    The name of first employee : First Employee
    The age of first employee : 24
    The salary of first employee : 10000.00
    



    Program Analysis







    Please share this article -

    Facebook Google Pinterest Reddit Tumblr Twitter




    < Prev
    Next >
    < Structure in C
    Array of structures >
    Please subscribe our social media channels for notifications, we post a new article everyday.

    Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

    Coming Next
    -
    C++ and Python

    Ad2