Challenge - 5 Problems
Structure Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing structure members
What is the output of this C++ code that uses a structure to store a person's data?
C++
#include <iostream>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
Person p = {"Alice", 30};
std::cout << p.name << " is " << p.age << " years old." << std::endl;
return 0;
}Attempts:
2 left
💡 Hint
Look at how the structure members are accessed using the dot operator.
✗ Incorrect
The structure Person holds two members: name and age. Accessing them with p.name and p.age prints the expected sentence.
🧠 Conceptual
intermediate1:30remaining
Why use structures instead of separate variables?
Why do programmers use structures in C++ instead of just separate variables for related data?
Attempts:
2 left
💡 Hint
Think about how grouping data helps in real life, like keeping all info about a person in one folder.
✗ Incorrect
Structures group related data into one unit, making code easier to read and maintain. They do not inherently speed up programs or replace functions.
❓ Predict Output
advanced2:00remaining
Output of nested structures
What will this C++ program print when using nested structures?
C++
#include <iostream>
#include <string>
struct Date {
int day;
int month;
int year;
};
struct Event {
std::string name;
Date date;
};
int main() {
Event e = {"Meeting", {15, 8, 2024}};
std::cout << e.name << " on " << e.date.day << "/" << e.date.month << "/" << e.date.year << std::endl;
return 0;
}Attempts:
2 left
💡 Hint
Look at how the nested structure Date is accessed inside Event.
✗ Incorrect
The Event structure contains a Date structure. Accessing e.date.day, e.date.month, and e.date.year prints the date correctly in day/month/year format.
🔧 Debug
advanced2:00remaining
Identify the error in structure initialization
What error does this C++ code produce when trying to initialize a structure?
C++
#include <iostream>
struct Point {
int x;
int y;
};
int main() {
Point p = (10, 20);
std::cout << p.x << ", " << p.y << std::endl;
return 0;
}Attempts:
2 left
💡 Hint
Check how the structure is initialized with parentheses and commas.
✗ Incorrect
The expression (10, 20) uses the comma operator and evaluates to 20 (int). Struct Point cannot be initialized from an int, causing a compilation error for invalid structure initialization. Use {10, 20} for aggregate initialization.
🧠 Conceptual
expert2:30remaining
Why structures improve code maintainability
How do structures help improve code maintainability in large C++ programs?
Attempts:
2 left
💡 Hint
Think about how grouping data helps when you need to change or add features later.
✗ Incorrect
Structures group related data, so changes happen in one place, reducing errors and duplication. They do not replace comments or affect compilation.