0
0
C++programming~20 mins

Nested structures in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Structures Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested struct member access
What is the output of this C++ code?
C++
struct Point {
    int x;
    int y;
};

struct Rectangle {
    Point topLeft;
    Point bottomRight;
};

#include <iostream>
int main() {
    Rectangle rect = {{1, 4}, {5, 1}};
    std::cout << rect.topLeft.x << "," << rect.bottomRight.y << std::endl;
    return 0;
}
A1,4
B5,4
C5,1
D1,1
Attempts:
2 left
💡 Hint
Look at how the nested points are initialized and which members are accessed.
Predict Output
intermediate
2:00remaining
Output of nested struct with array member
What will this program print?
C++
struct Team {
    struct Player {
        int id;
        int score;
    } players[3];
};

#include <iostream>
int main() {
    Team team = {{{1, 10}, {2, 20}, {3, 30}}};
    std::cout << team.players[1].score << std::endl;
    return 0;
}
A10
B20
C30
D1
Attempts:
2 left
💡 Hint
Check which player index is accessed and which member is printed.
🔧 Debug
advanced
2:00remaining
Identify the error in nested struct initialization
This code tries to initialize nested structs but causes a compilation error. What is the error?
C++
struct Date {
    int day;
    int month;
    int year;
};

struct Event {
    char name[20];
    Date date;
};

int main() {
    Event e = {"Meeting", {12, 5}};
    return 0;
}
AStruct Event cannot contain another struct
BCannot initialize char array with string literal
CMissing year value in nested Date initialization
DMissing semicolon after struct definitions
Attempts:
2 left
💡 Hint
Check how many values are needed to initialize Date.
📝 Syntax
advanced
2:00remaining
Correct syntax to access nested struct member
Which option correctly accesses the 'z' member inside nested structs?
C++
struct Inner {
    int z;
};

struct Outer {
    Inner inner;
};

Outer o = {{5}};
Ao.inner.z
Bo->inner.z
Co.inner->z
Do->inner->z
Attempts:
2 left
💡 Hint
Remember the difference between dot (.) and arrow (->) operators.
🚀 Application
expert
3:00remaining
Calculate total price from nested structs
Given the structs below, what is the total price printed by the program?
C++
struct Item {
    char name[10];
    int quantity;
    double price_per_unit;
};

struct Order {
    Item items[2];
};

#include <iostream>
int main() {
    Order order = {{{"Pen", 10, 1.5}, {"Notebook", 5, 3.0}}};
    double total = 0;
    for (int i = 0; i < 2; ++i) {
        total += order.items[i].quantity * order.items[i].price_per_unit;
    }
    std::cout << total << std::endl;
    return 0;
}
A30
B25
C20
D35
Attempts:
2 left
💡 Hint
Multiply quantity by price for each item and add them up.