structure programs in C++

Here in this page, we will discuss two following programs,

to know structure size using operator

As mentioned earlier, we can find out the size of any data-type or variable from the sizeof operator.

The sizeof operator has also been used in the program given below.

To know the size of a structure, we first declare the structure-variable. The size of this structure-variable is the size of the structure itself.

Here is an example,

#include<conio.h>
#include<iostream.h>

struct size
  {
   int a;   // 2byte
   float b;  //4 byte
   char c;  //1 byte
 }x;

void main()
{
  cout<<"size of structure(in byte): "<<sizeof(x);
  getch();
}
OUTPUT:-
size of structure(in byte): 7

Explanation:-

In the program, three types of data-member (int, float and char) of the structure test are declared and we know how much space they reserve in the data-type memory.

  So here all the data-members total size

int + float + char = structure variable size

such as,

2 + 4 + 1 = 7 bytes, 

will be the size of the structure.


 

Store a student detail and subjects using Structure and display them

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

struct student 
{
    // data member declaration
        int roll,age;
        char st_name[20];
        char f_name[20];
        char sub [30];
       
   // function member declaration
        void get_subject();
        void show_subject();
}x;

void main(void)
{ 
   // storing personal information
    clrscr();
    cout<<"Enter Roll no: ";
    cin>>x.roll;
    cout<<"Enter Stu.age: ";
    cin>>x.age;
    cout<<"Enter Stu name: ";
    gets(x.st_name);
    cout<<"Enter Fa. name: ";
    gets(x.f_name);

    cout<<endl;

    x.get_subject(); // calling function

clrscr();    

// display record after screen clear
    cout<<"\nShow Record";
    cout<<"\nStudent Roll no: "<<x.roll;
    cout<<"\nStudent age : "<<x.age;
    cout<<"\nStudent Name : "<<x.st_name;
    cout<<"\nStu. father name: "<<x.f_name<<endl;

    x.show_subject();
    getch();
}
void student::get_subject()
{  
    cout<<"\nEnter Subject Detail:\n";

    for(int i=0; i<5; i++)
    {
       cout<<"Enter "<<i+1<<" subject name: ";
       cin>>x.sub[i];                       // store subject name
    }
}
void student::show_subject()
{
    cout<<"Display Subject name: \n";

    for(int i=0; i<5; i++)
    {
      cout<<i+1<<" subject name: "<<x.sub[i]<<endl;   // display subject name   
    }
}
OUTPUT:-
Enter Roll no: 101
Enter Stu.age: 23
Enter Stu name:Rohit sherma
Enter Fa. name:Rakesh sherma 

Enter Subject Detail:
Enter 1 subject name: hindi
Enter 2 subject name: english
Enter 3 subject name: math
Enter 4 subject name: physics
Enter 5 subject name: chemistry

Show Record
Student Roll no: 101
Student  age   : 23
Student Name   : Rohit sherma
Stu. father name: Rakesh sherma

Display Subject name: 
1 subject name: hindi
2 subject name: english
3 subject name: math
4 subject name: physics
5 subject name: chemistry