The structure is defined as a collection of different data type elements under a common name. It is similar to a class as the class and structure can hold elements of different types.
The struct
keyword defines a structure followed by an identifier. Then we can add the structure members using curly braces. For example:
struct people
{
char name[50];
int age;
float salary;
};
In this example, we have made a structure with the name 'people' and have the members as 'name', 'age', 'salary'
Here we are creating a structure called student and name, roll and marks as its data members. Then create a structure variable s. Ask the user to enter the details of the student data like name, roll, and marks. Store these data taken from the user in data members of s. Finally, display the data entered by the user on the screen.
Step 1: Call the header file iostream.
Step 2: Use the namespace std.
Step 3: Create a structure student
Step 4: Create data members, name, roll, and marks
Step 5: Open the integer type main function; int main().
Step 6: Create a structure variable s
Step 7: prompt the user to enter the data of the student.
Step 8: Store the entered details in the data members.
Step 9: Display the details on the screen
Step 10: Exit
#include <iostream>
using namespace std;
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
student s;
cout << "Enter information," << endl;
cout << "Enter name: ";
cin >> s.name;
cout << "Enter roll number: ";
cin >> s.roll;
cout << "Enter marks: ";
cin >> s.marks;
cout << "\nDisplaying Information," << endl;
cout << "Name: " << s.name << endl;
cout << "Roll: " << s.roll << endl;
cout << "Marks: " << s.marks << endl;
return 0;
}
Enter information, Enter name: John Enter roll number: 007 Enter marks: 99% Displaying Information, Name: Shyn Roll: 7 Marks: 99