Workshop: Modeling Real-World Entities with Structures and Unions

UPI Study › Courses › Programming in C › Free lessons › Lesson 10.7 Free with a free account

Workshop: Modeling Real-World Entities with Structures and Unions

Programming in C · Chapter 10: Structures, Unions, and Compound Data ModelingSection 10.7 · lesson 70 of 787 min · free with a free account

← The Union Data Type in CNext lesson: Singly Linked List Fundamentals →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Validating struct data, tagged union makers, and a counted inventory.

  • Write validation functions so a struct is filled only when every field passes
  • Build maker functions that set a tagged union's tag and member together
  • Manage an array of structs with a count that tracks the used slots
  • Compute a report of income per record and a grand total

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (989 words). Read along, or search it.

The Challenge

Letting Only Good Data In

A struct will hold anything, even nonsense: a machine with no name, or one that costs minus five tokens a play. The computer stores it happily. So a careful programmer builds a front door that lets only good data in. In this workshop, you'll build three small programs for the Starlight Arcade. A machine that checks its own fields, a prize that's one of three kinds, and a floor inventory with a report.

Program One Plan

Two Rules for an Arcade Machine

Program one: a machine that checks itself. struct Machine keeps a name, and the tokens one play costs. The name gets at most 15 letters, because the sixteenth box holds the null character that ends the string, as in 7.5. Two rules protect it. The name can't be empty or too long, and the cost can never be negative. Zero is fine: a free play. Each rule gets a small function that answers 1 for good, and 0 for bad. And make_machine is the front door. It fills the struct only when both answers are yes.

Program One Code

Validating Before Filling the Struct

The functions follow the plan, one for one. valid_name measures the name with string length, and accepts 1 to 15. valid_cost accepts any cost of zero or more. make_machine receives the address of the struct to fill, as in 10.5. Then it asks both questions, before it writes anything. Only then does it copy the name, with snprintf, which stops at the sixteen boxes, whatever it's handed. show_machine takes a const pointer, because it only reads. Sam's four tests: one good machine, an empty name, a name that's too long, and a negative cost. Build and run. Rocket Race gets in, at 3 tokens a play. The other three are turned away, each with its reason.

Quick Check

Sixteen Characters Is One Too Many

Quick check. Sam tests the two rules on their own. Turbo Tank Blitz has sixteen characters, Turbo Tank has ten, and the cost is zero. What three numbers does it print? Pause and predict. Build and run: 0, 1, 1. Sixteen characters is one too many: a 16-box name array needs its last box for the null character. Ten is fine. And a cost of zero passes, because only negative costs are turned away. A free play is allowed.

Program Two Plan

One Maker Function per Prize Kind

Program two: a prize that's one of three things. From 10.6, that's a tagged union: an enum tag, plus a union. The new idea is one maker function per kind, with three jobs: check the value, set the tag, and store the member. Tokens must be 1 to 1000. A toy name, 1 to 15 letters. And a discount, 1 to 90 percent. If the tag and the member are always set together, they can't get out of step. So the display function can trust the tag.

Program Two Code

Check, Set the Tag, Store the Member

Here's the code. The enum and the struct, folded here, are the ones from 10.6. make_tokens checks first. If the value is out of range, it returns 0, and leaves the prize untouched. Otherwise it sets the tag, and then the member, one right after the other. make_toy and make_discount follow the same three steps. show_prize is the switch from 10.6. It reads only the member that the tag names. In main, one variable, p, serves all three prizes. Each maker overwrites the shared spot, and the tag along with it. Build and run: 25 bonus tokens, a Robot toy, 20 percent off, and the discount of 150 is rejected.

Quick Check

A Rejected Value Leaves the Prize Intact

Quick check. First, make_toy fills p. Then make_tokens is asked for 5000 tokens. What does show_prize print? Pause and predict. It prints a Rubber Duck toy. 5000 is out of range, so make_tokens returns 0 before it touches anything. The tag and the toy name stay as they were, still in step. That's why each maker checks first, and only then sets the tag and the member.

Program Three Plan

An Array of Machines Plus a Count

Program three: the floor inventory. The arcade floor holds up to 4 machines. Priya keeps them in an array of structs, as in 10.3, plus an int called count: how many slots are in use. Slots 0 up to count minus 1 hold real machines. The rest are empty. So one number does two jobs. With two machines in, count is 2. That's how many there are, and slot 2 is where the next one goes.

Adding Machines

Checking Room and Fields Before Writing

add_machine checks for room first. If count has reached MAX, the floor is full, and nothing is written. Next it checks the fields: a name of 1 to 15 letters, and no negative tokens or plays. Only then does it fill the next free slot, list at count. And it adds 1 to count. count arrives as an int star, so star count, plus plus, changes the caller's own number. And list is really an address, as in 7.3. So the slots being filled are in the caller's real array.

Report

Income per Machine and Grand Total

report loops from 0 up to count, and works out each machine's income: tokens per play, times plays. It prints one row for each machine. After the loop, it prints the grand total, the sum of every income. main tries six machines. One has an empty name, and the sixth won't fit. Build and run. The empty name is rejected, and Air Hockey finds the floor full. Four machines made it in: 360, plus 170, plus 240, plus 200. That's 970 tokens.

Key Takeaways

Validate First, Then Fill

To sum up. Check every field first, and fill a struct only when all of them pass. Give each kind of a tagged union its own maker, which sets the tag and the member together. Keep an array of structs with a count: how many are in use, and where the next one goes. And give functions that only read a const pointer.

Try It

Three Challenges to Extend the Arcade

Three challenges to try on your own. First, add plays to machine.c, with a check that rejects negative numbers. Second, add a fourth prize kind, a free-play pass. Build before you add its case, and read clang's warning. Third, write a function that finds the busiest machine on the floor.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Workshop: Modeling Real-World Entities with Structures and Unions

How do you validate data before storing it in a struct in C?
Write a small check function for each rule, returning 1 for valid and 0 for invalid, and call them all before writing anything. A make_machine function, for example, can require a name of 1 to 15 characters and a cost of zero or more. Only when every check passes does it copy the name with snprintf and set the cost, so bad data never enters the struct.
How do you keep a tagged union's tag and value in sync?
Give each kind its own maker function that does three things in order: check the value, set the tag, and store the member. If the value is out of range, the maker returns 0 before touching anything. For example, asking make_tokens for 5000 when the limit is 1 to 1000 leaves an earlier toy prize, both tag and name, exactly as it was.
How do you add records to a fixed-size array of structs in C?
Keep an int count of the used slots. Slots 0 to count minus 1 hold real records, and slot count is where the next one goes. An add function first checks that count is below the maximum, then validates the fields, then fills list[count] and increments the count. Passing count as an int pointer lets the function update the caller's variable with (*count)++.
How do you calculate a value for each record in an array of structs?
Loop from 0 up to count, combine each record's own fields, and add the result to a running total. For arcade machines, income is tokens per play times plays. Four machines earning 360, 170, 240, and 200 tokens give a grand total of 970. Taking the array through a const pointer shows that the report function only reads the records.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →