All about C plus plus algorithms!

Saturday 29 October 2016

Introduction to Struct || C++ (C plus plus)


What is a Struct?

                               A struct is a data type that contains elements within it. Think of a data type that has to store the information of a student. Now, it can't be simply int  or  char, instead it consists of both. For example a student's profile has a name, roll number, GPA, faculty. It looks like this :

char name[25];  // using dynamic char array to store name
int roll_num;    
float gpa;
char faculty[25]; 

Now, we need to store all of this together so that we can easily access it. C++ allows you to make your own data types for this purpose, they are called STRUCTS (derived from Structure probably :P ). It is simple. See below :

struct student
{
     char name[25]; 
     int roll_num;    
    float gpa;
    char faculty[25]; 
};    //dont't forget to add ; at the end of it


PS : Define it globally if you want to use it in functions other than the Main().

How would you use it?
Unlike int  or char, you have to assign every element the data one-by-one. We use dot operator for this purpose.

Let's try an example.
First define a student type object as :

student s;     // I'll name it 's' here

Now to assign data, we write syntax like this :

Strcpy(s.name, "Eugene");    //using String copy instruction for this purpose
s.roll_num = 1234;
s.gpa = 3.12;
Strcpy(s.faculty, "ComputerSciences");


You can similarly display it on the screen like

cout << "Roll number : " << s.roll_num;

You can also make arrays of structs like student s_arr[25] which is an array of 25 students. Same goes for Dynamic arrays.

NOTE : When you define a dynamic object of the struct, use Arrow operator (->) to access the elements e.g.

student* s_arr[5];
s_arr[0] -> roll_num  = 123;   //which is the pointer to the first student that's on the 0th index.
                                                 // to access its roll number, we used Arrow Operator.
                                               // similarly we can access name, gpa or faculty.




Share:

0 comments:

Post a Comment

Popular Posts

Blog Archive

Copyright by progrithms.blogspot.com. All Rights Reserved.. Powered by Blogger.

Copyright © Programs and Algorithms | Powered by Blogger

Design by ThemePacific | Blogger Theme by NewBloggerThemes.com