SwS&Structre To Function
SwS&Structre To Function
#include <iostream>
using namespace std;
// Define the Address structure
struct Address {
string street;
string city;
int zipCode;
};
// Define the Person structure
struct Person {
string name;
int age;
Address address; // Nested Address structure
};
int main() {
// Create a Person object
Person person = {"John", 20, {"123 Elm Street", "Springfield", 98765}};
// Access nested structure members
cout << "Name: " << person.name << endl;
cout << "Age: " << person.age << endl;
cout << "Street: " << person.address.street << endl;
cout << "City: " << person.address.city << endl;
cout << "ZIP Code: " << person.address.zipCode << endl;
return 0;
}
STRUCTURE & Function OR Accessing structure through Function
#include <iostream>
using namespace std;
// Define a structure for Book
struct Book {
string title;
string author;
float price;
int nopages;
};
// Function to display book details
syntax: function type function name (variable type variable name)
void displayBookDetails(Book b) {
cout << "--- Book Details ---" << endl;
cout << "Title: " << b.title << endl;
cout << "Author: " << b.author << endl;
cout << "Price: $" << b.price << endl;
}
//Compiler entry point-------à
int main() {
// Create a Book object
Book myBook;
// Input book details
cout << "Enter book title: ";
getline(cin, myBook.title); //getline is used to input string only
cout << "Enter book author: ";// myBook is the object of Book structure
getline(cin, myBook.author);
cout << "Enter book price: ";
cin >> myBook.price;
cout << "Enter no. of pages in book: ";
cin >> myBook.nopages;
// Pass structure to function
displayBookDetails(myBook);
return 0;
}