C++ Structures – Detailed Instructions From A-Z

A compound data type called structure comprises various variables of various types. For instance, you could want to save student information like name, roll number, and age. There are two methods to go about it. The first is to make separate variables for each piece of data, but this method has the drawback that it is impractical if you need to store the information on several students.
The second and ideal method involves putting together a framework similar to this:

struct Student
    char stuName[30];
    int stuRollNo;
    int stuAge;

Now that all three of these members are merged, you may construct a structural variable by doing something like this:

structure_name variable_name

In order to use this structure to retain the data of two students, you may do it as follows:

Student s1, s2;

I can then access the students in the Student hierarchy as follows:

//Assigning name to first student
s1.stuName = "Ajeet";
//Assigning age to the second student
s2.stuAddr = 22;

For each student, I may similarly change and retrieve the values of other data elements in the structure. To put this all together, let’s look at an example in its entirety:

Structure Example in C++

#include <iostream>
using namespace std;
struct Student{
   char stuName[30];
   int stuRollNo;
   int stuAge;
int main(){
   Student s;
   cout<<"Enter Student Name: ";
   cin.getline(s.stuName, 30);
   cout<<"ENter Student Roll No: ";
   cout<<"Enter Student Age: ";
   cout<<"Student Record:"<<endl;
   cout<<"Name: "<<s.stuName<<endl;
   cout<<"Roll No: "<<s.stuRollNo<<endl;
   cout<<"Age: "<<s.stuAge;
   return 0;


Enter Student Name: Negan
ENter Student Roll No: 4101003
Enter Student Age: 22
Student Record:
Name: Negan
Roll No: 4101003
Age: 22

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button