What is Structure in C++?
C++ Structure is a collection of same / different data types. It is a user-defined data type. Each variable in the structure is known as a member of the structure.
Syntax:-
struct structure_Name { member1; member2; . . . memberN; };
Example 1:-
Passing structure to function.
Passing a structure student to the function display_student() and printing the details of the student using the structure variable.
Code:
C++ Code
#include "bits/stdc++.h"
using namespace std;
struct student {
int Register_no;
string name;
float marks;
char grade;
};
void display_student(student s) {
cout << "Student Details:- " << '\n';
cout << "Register Number: " << s.Register_no << '\n';
cout << "Name: " << s.name << '\n';
cout << "Marks: " << s.marks << '\n';
cout << "Grade: " << s.grade << '\n';
}
int main() {
student s;
cout << "Enter Register Number:- " << '\n';
cin >> s.Register_no;
cout << "Enter the Name:- " << '\n';
cin >> s.name;
cout << "Enter the mark:- " << '\n';
cin >> s.marks;
cout << "Enter the grade:- " << '\n';
cin >> s.grade;
//Function call with structure variable as an argument
display_student(s);
return 0;
}
Sample Input:-
Enter Register Number:- 211
Enter the Name:- JAI
Enter the mark:- 100
Enter the grade:- A
Sample Output:-
Student Details:-
Register Number: 211
Name: JAI
Marks: 100
Grade: A
Example 2:-
Returning structure from function.
In the below example input_student() function will take the input structure from the user, assign them to structure members, and returns the structure, and another function display_student() which takes the structure student as an argument and prints the details of the student.
Code:
C++ Code
#include "bits/stdc++.h"
using namespace std;
struct student {
int Register_no;
string name;
float marks;
char grade;
};
void display_student(student s) {
cout << "\nStudent Details:- " << '\n';
cout << "Register Number: " << s.Register_no << '\n';
cout << "Name: " << s.name << '\n';
cout << "Marks: " << s.marks << '\n';
cout << "Grade: " << s.grade << '\n';
}
student input_student(student s) {
cout << "Enter Register Number:- " << '\n';
cin >> s.Register_no;
cout << "Enter the Name:- " << '\n';
cin >> s.name;
cout << "Enter the mark:- " << '\n';
cin >> s.marks;
cout << "Enter the grade:- " << '\n';
cin >> s.grade;
return s;
}
int main() {
student s;
s = input_student(s);
//Function call with structure variable as an argument
display_student(s);
return 0;
}
Sample Input:-
Enter Register Number:- 212
Enter the Name:- Ganesh
Enter the mark:- 80
Enter the grade:- B
Sample Output:-
Student Details:-
Register Number: 212
Name: Ganesh
Marks: 80
Grade: B
Special thanks to JAIGANESH R S for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article. If you want to suggest any improvement/correction in this article please mail us at [email protected]