Challenge - 5 Problems
Nested Structures Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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;
}Attempts:
2 left
💡 Hint
Look at how the nested points are initialized and which members are accessed.
✗ Incorrect
The Rectangle struct has two Points: topLeft and bottomRight. topLeft.x is 1, bottomRight.y is 1, so output is '1,1'.
❓ Predict Output
intermediate2: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;
}Attempts:
2 left
💡 Hint
Check which player index is accessed and which member is printed.
✗ Incorrect
players[1] is the second player with id=2 and score=20, so output is 20.
🔧 Debug
advanced2: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;
}Attempts:
2 left
💡 Hint
Check how many values are needed to initialize Date.
✗ Incorrect
Date requires three integers (day, month, year), but only two are provided, causing a compilation error.
📝 Syntax
advanced2: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}};Attempts:
2 left
💡 Hint
Remember the difference between dot (.) and arrow (->) operators.
✗ Incorrect
o is an object, so use dot operator to access members. Arrow operator is for pointers.
🚀 Application
expert3: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;
}Attempts:
2 left
💡 Hint
Multiply quantity by price for each item and add them up.
✗ Incorrect
Pen: 10 * 1.5 = 15, Notebook: 5 * 3.0 = 15, total = 30.0