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>It is easy to understand program given above. Now we will write same thing with the use of struct.
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);
}
#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!!