Structures (struct
) in C++ are used to group related variables of different data types together.
1️⃣ Area of Rectangle using Structure
📌 Define a structure to calculate the area of a rectangle.
#include <iostream>
using namespace std;
struct Rectangle {
double length;
double width;
};
int main() {
Rectangle rect;
cout << "Enter length and width: ";
cin >> rect.length >> rect.width;
double area = rect.length * rect.width;
cout << "Area of Rectangle: " << area;
return 0;
}
🔹 Output
Enter length and width: 5 10
Area of Rectangle: 50
2️⃣ Book Information using Structure
📌 Define a structure to store and display book details.
#include <iostream>
using namespace std;
struct Book {
string title;
string author;
double price;
};
int main() {
Book b;
cout << "Enter Book Title: ";
getline(cin, b.title);
cout << "Enter Author: ";
getline(cin, b.author);
cout << "Enter Price: ";
cin >> b.price;
cout << "\nBook Details:\n";
cout << "Title: " << b.title << "\nAuthor: " << b.author << "\nPrice: $" << b.price;
return 0;
}
🔹 Output
Enter Book Title: The Alchemist
Enter Author: Paulo Coelho
Enter Price: 15.99
Book Details:
Title: The Alchemist
Author: Paulo Coelho
Price: $15.99
3️⃣ Person Information using Structure
📌 Define a structure to store and display a person's information.
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
string city;
};
int main() {
Person p;
cout << "Enter Name: ";
getline(cin, p.name);
cout << "Enter Age: ";
cin >> p.age;
cin.ignore();
cout << "Enter City: ";
getline(cin, p.city);
cout << "\nPerson Information:\n";
cout << "Name: " << p.name << "\nAge: " << p.age << "\nCity: " << p.city;
return 0;
}
🔹 Output
Enter Name: John Doe
Enter Age: 30
Enter City: New York
Person Information:
Name: John Doe
Age: 30
City: New York
4️⃣ Student Information using Structure
📌 Define a structure to store and display student details.
#include <iostream>
using namespace std;
struct Student {
string name;
int rollNumber;
double marks;
};
int main() {
Student s;
cout << "Enter Student Name: ";
getline(cin, s.name);
cout << "Enter Roll Number: ";
cin >> s.rollNumber;
cout << "Enter Marks: ";
cin >> s.marks;
cout << "\nStudent Information:\n";
cout << "Name: " << s.name << "\nRoll Number: " << s.rollNumber << "\nMarks: " << s.marks;
return 0;
}
🔹 Output
Enter Student Name: Alice
Enter Roll Number: 101
Enter Marks: 95.5
Student Information:
Name: Alice
Roll Number: 101
Marks: 95.5
📌 Summary
✔ Structures help group multiple variables into a single unit.
✔ Use cin
, getline(cin, variable)
, and cin.ignore()
for user input.
✔ Nested structures can be used for complex data.
🚀 Need more examples? Let me know! 🔥
0 Comments