structure with function 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++

#include<iostream>
#include<stdio>
using namespace std;

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;

int main(void)
 { 
   // storing personal information
 
    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
    

// 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();
return 0;
}
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

Explanation

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.

Related exercise

Like it?

Leave a Reply

Your email address will not be published.