Accessing structure elements

'.' => member or dot operator to access the pages of the structure book :

b1.pages

Similarly to refer to price

b1.price

Example :

#include<stdio.h>
#include<conio.h>
void main( )
{
    struct book
    {
        char name;
        float price;
        int pages;
    };
    struct book b1 = { 'B', 130.00, 550 };
    printf ("\nName of the book = %c", b1.name);
    printf ("\nPrice of book = %f", b1.price);
    printf ("\nNumber of pages in the book = %d", b1.pages);
    printf ("\nAddress of name = %u", &b1.name);
    printf ("\nAddress of price = %u", &b1.price);
    printf ("\nAddress of pages = %u", &b1.pages);
}

Output :
Name of the book = B
Price of book = 130.00
Number of pages in the book = 550
Address of name = 65518
Address of price = 65519
Address of pages = 65523



Example of User Input :

#include <stdio.h>
int main(void)
{
    struct book
    {
    char name[10];
    int price;
    }b1[5];

    int i;
    for(i=0;i<2;i++)
    {
        Printf(“\nEnter Book name : ”);
        scanf("%s",b1[i].name);

        printf(“\nEnter Price :”);
        scanf("%d",&b1[i].price);
    }
    for(i=0;i<2;i++)
    {
        printf("\nName is : %s",b1[i].name);
        printf("\nPrice : %d ",b1[i].price);
    }

    return 0;
}

Output :
Enter Book name :
Abc
Enter Price :
100
Enter Book Name :
Pqr
Enter price
50
Name is : Abc
Price : 100
Name is : Pqr
Price : 50

Explanation :
Here b1[5] means b1 is structure variable and size is defined as 5 means we can store 5 book details in the memory. So here we are storing 2 book details with its name and price. 
For loop is used to get the 2 book details.

Post a Comment

0 Comments