Structures in C++ allow us to group related data together. We can also use functions to operate on structures.
1️⃣ Area of Rectangle using Structure & Function
📌 Using a function to calculate and return the area of a rectangle.
#include <iostream>
using namespace std;
struct Rectangle {
double length, width;
};
double calculateArea(Rectangle r) {
return r.length * r.width;
}
int main() {
Rectangle rect;
cout << "Enter Length and Width: ";
cin >> rect.length >> rect.width;
cout << "Area of Rectangle: " << calculateArea(rect) << endl;
return 0;
}
🔹 Output
Enter Length and Width: 5 10
Area of Rectangle: 50
📌 Key Points:
✔ Function calculateArea()
receives a structure object as a parameter.
✔ The function returns the area after calculation.
2️⃣ Show Book Information using Structure & Function
📌 Using a function to display book details.
#include <iostream>
using namespace std;
struct Book {
string title;
string author;
double price;
};
void displayBook(Book b) {
cout << "\nBook Details:\n";
cout << "Title: " << b.title << "\nAuthor: " << b.author << "\nPrice: $" << b.price << endl;
}
int main() {
Book book;
cout << "Enter Book Title: ";
getline(cin, book.title);
cout << "Enter Author: ";
getline(cin, book.author);
cout << "Enter Price: ";
cin >> book.price;
displayBook(book);
return 0;
}
🔹 Output
Enter Book Title: C++ Basics
Enter Author: John Smith
Enter Price: 29.99
Book Details:
Title: C++ Basics
Author: John Smith
Price: $29.99
📌 Key Points:
✔ displayBook()
function takes a structure as an argument.
✔ Pass-by-value is used to avoid modifying the original structure.
3️⃣ Show Person Information using Structure & Function
📌 Using a function to display person details.
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
string city;
};
void displayPerson(const Person &p) {
cout << "\nPerson Details:\n";
cout << "Name: " << p.name << "\nAge: " << p.age << "\nCity: " << p.city << endl;
}
int main() {
Person person;
cout << "Enter Name: ";
getline(cin, person.name);
cout << "Enter Age: ";
cin >> person.age;
cin.ignore();
cout << "Enter City: ";
getline(cin, person.city);
displayPerson(person);
return 0;
}
🔹 Output
Enter Name: Alice Johnson
Enter Age: 25
Enter City: New York
Person Details:
Name: Alice Johnson
Age: 25
City: New York
📌 Key Points:
✔ displayPerson()
function takes a constant reference (const Person &p
) to prevent modifications and improve efficiency.
✔ cin.ignore()
is used to clear the buffer before getline()
.
📌 Summary
✔ Functions can take structures as parameters.
✔ Use pass-by-value when you don't want changes in the original structure.
✔ Use pass-by-reference (const &
) for efficiency.
✔ Functions improve code reusability and modularity.
🚀 Need more examples? Let me know! 🔥
0 Comments