Function with structure in C++

Here we will learn about function with structure in C++ with the help of a Example store a student Details and subjects detail using structure.

In the Program function will be a member of a structure this is the also the main difference between C and C++ language.

In the program we store student Age, Student Name , Father Name in normal way while storing subject details we used the function.

Here is the Program,

Store a student detail and subjects using structure with function in C++


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();

void main(void)
   // storing personal information
    cout<<"Enter Roll no: ";
    cout<<"Enter Stu.age: ";
    cout<<"Enter Stu name: ";
    cout<<"Enter Fa. name: ";


    x.get_subject(); // calling function


// 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;

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   
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


In the program we used two function inside the structure get_subject() and show_subject().

after storing Personal detail function get_subject() will called and will be ask to the user for entered the subject detail, and in the same order Record will be display on the console.