structre (struct) in c++ with examples

Image result for c++Going forward with C/C++ programming language tutorial today we will learn about structure(struct). Till now we have learned about many datatypes like int, char, float, double etc. These all datatypes store data in some format. If we want to store names of people, we can store in char array, If we want to store ages of people, we can store in int array but if we want to store length and width of rectangles(storing rectangle) then there are 2 ways. One is make 2 variables and store length and width on them. If we want to store multiple rectangles then we have to make 2 arrays, one for length and another for width. Using struct one rectangle can be stored in one variable and Rectangles can be stored in one array.

Lets see the program which does not use struct to store length and width of a rectangle. Later we will see better version which uses struct.
#include <stdio.h>

int
main() {
int
length1 = 12;
int
width1 = 8;

int
length2 = 20;
int
width2 = 11;

printf("Rectangle1: %d %d\n", length1, width1);
printf("Rectangle2: %d %d\n", length2, width2);

scanf("%d", &length1);
}
It is easy to understand program given above. Now we will write same thing with the use of struct.
#include <stdio.h>

struct
Rectangle {
int
length;
int
width;
};

int
main() {
struct
Rectangle rect1;
struct
Rectangle rect2;
rect1.length = 12;
rect1.width = 8;  
rect2.length = 20;
rect2.width = 11;

printf("Rectangle1: %d %d\n", rect1.length, rect1.width);
printf("Rectangle2: %d %d\n", rect2.length, rect2.width);

scanf("%d", &(rect1.length));
}


Here we have defined a struct named Rectangle which contains 2 variables width and height. Here Rectangle becomes a datatype like int, char. This Rectangle datatype can store 2 int: height and width. To define new datatype Rectangle see above how we have done it. struct Rectangle { ... };
This have defined a new datatype Rectangle. To use it and make a variable of type Rectangle as shown in main(){...} Here two variable rect1 and rect2 of Rectangle type have been defined. Each of two variable can have length and width. To access length and width of rect1 we use rect1.length and rect1.width.

Using struct we can make any kind of object which can store several variables.
If you liked this blog, tell your friends also because it can useful to them also!!