DATA STRUCTURE AND ALGORITHM (Structure)
STRUCTURE
Structures in C++ are user defined data types which are used to store group of items of non-similar data types.
Def:
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.
Syntax Of Structure:
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};Structures in C++ can contain two types of members:
- Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++.
- Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration.
In the above structure, the data members are three integer variables to store roll number, age and marks of any student and the member function is printDetails() which is printing all of the above details of any student.
Variable declaration with structure declaration:
struct Point { int x, y; } p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data types struct Point { int x, y; }; int main() { struct Point p1; // The variable p1 is declared like a normal variable }Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.How to access structure elements?#include <iostream>using namespace std;struct Point {int x, y;};int main(){struct Point p1 = { 0, 1 };// Accessing members of point p1p1.x = 20;cout << "x = " << p1.x << ", y = " << p1.y;return 0;}Output:x = 20, y = 1What is an array of structures?
#include <iostream> using namespace std; struct Point { int x, y; }; int main() { // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << " " << arr[0].y; return 0; }


Comments
Post a Comment