Small Steps V — Making Your Own Types
Group Values with Structs
Group Values with Structs
Explore one topic in small steps. Try the examples one at a time and take a break whenever you need. Choose how many extra exercises you want to try.
Grouping related values
What you will learn
struct defines a new type grouping related values. Put a name and score together in one Player.
Try it
struct Player
{
String name;
int score;
};
void small_main()
{
Player player;
player.name = "Alex";
player.score = 1200;
print(player.name, ": ", player.score);
}
String and int are existing types; Player is a type we create. Access the values inside it with a dot, as in player.name.
The example prints Alex: 1200. A struct definition needs a ; after its closing brace.
Storing several grouped values
What you will learn
A type you create can also be an array element. Array<Player> holds information about several players.
Try it
struct Player
{
String name;
int score;
};
void small_main()
{
Array<Player> players = {
{"Alex", 800},
{"Mina", 1200},
{"Sam", 950}
};
int best = 0;
for (int i = 1; i < players.length(); i = i + 1)
if (players[i].score > players[best].score)
best = i;
print("Winner: ", players[best].name);
}
players[i].score is the score of player i. Reuse the method for finding a maximum's position, then print that player's name at the end.
The expected result is Winner: Mina. Change the scores and check that the winner changes.
Exercise
Create a Point struct with double x and y. Store (3.5, 7.0) and print the values.
struct Point
{
// Add x and y here.
double x;
double y;
};
void small_main()
{
Point point;
point.x = 3.5;
point.y = 7.0;
print(point.x, ", ", point.y);
}
Hint
Start with struct Point { double x; double y; };.
show solution
struct Point
{
double x;
double y;
};
void small_main()
{
Point point;
point.x = 3.5;
point.y = 7.0;
print(point.x, ", ", point.y);
}
Try More (Optional)
Exercise
Put three Players with name and score in an Array and print the name of the Player with the highest score.
struct Player
{
String name;
int score;
};
void small_main()
{
Array<Player> players = {
{"A", 10},
{"B", 35},
{"C", 20}
};
// find and print the best player's name.
}
Hint
Use the lesson's best-index pattern.
show solution
struct Player
{
String name;
int score;
};
void small_main()
{
Array<Player> players = {
{"A", 10},
{"B", 35},
{"C", 20}
};
int best = 0;
for (int i = 1; i < players.length(); i = i + 1)
if (players[i].score > players[best].score)
best = i;
print(players[best].name);
}