0% found this document useful (0 votes)
4 views

Basic_Struct_Programs

struct c++

Uploaded by

ayeshaarif1567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Basic_Struct_Programs

struct c++

Uploaded by

ayeshaarif1567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Structs Practice Programs with Explanations

Simple Struct Example

**Code:**

#include <iostream>

using namespace std;

struct Student {

string name;

int age;

float marks;

};

int main() {

Student s1;

s1.name = "John";

s1.age = 20;

s1.marks = 85.5;

cout << "Student Name: " << s1.name << endl;

cout << "Student Age: " << s1.age << endl;

cout << "Student Marks: " << s1.marks << endl;

return 0;

Page 1
Structs Practice Programs with Explanations

**Explanation:**

This program defines a `Student` struct with three members: `name`, `age`, and `marks`. It then

creates an instance of `Student`, assigns values to its members, and prints them.

Structs with Arrays

**Code:**

#include <iostream>

using namespace std;

struct Student {

string name;

int age;

float marks;

};

int main() {

Student students[3];

students[0] = {"John", 20, 85.5};

students[1] = {"Alice", 19, 90.3};

students[2] = {"Bob", 21, 78.2};

for (int i = 0; i < 3; i++) {

Page 2
Structs Practice Programs with Explanations

cout << "Student " << i + 1 << ": " << students[i].name << ", Age: " << students[i].age << ",

Marks: " << students[i].marks << endl;

return 0;

**Explanation:**

This program defines a `Student` struct and creates an array of `Student` instances. It assigns

values to the elements of the array and then prints the details of each student using a for loop.

Nested Structs

**Code:**

#include <iostream>

using namespace std;

struct Address {

string city;

int zip;

};

struct Student {

Page 3
Structs Practice Programs with Explanations

string name;

int age;

float marks;

Address address;

};

int main() {

Student s1;

s1.name = "John";

s1.age = 20;

s1.marks = 85.5;

s1.address.city = "New York";

s1.address.zip = 10001;

cout << "Student Name: " << s1.name << endl;

cout << "Student Age: " << s1.age << endl;

cout << "Student Marks: " << s1.marks << endl;

cout << "Student City: " << s1.address.city << endl;

cout << "Student ZIP: " << s1.address.zip << endl;

return 0;

**Explanation:**

Page 4
Structs Practice Programs with Explanations

This program demonstrates nested structs by defining an `Address` struct and including it as a

member of the `Student` struct. It assigns values to the nested struct members and prints them.

Page 5

You might also like