Workshop: A Stack and Queue System | Programming in C

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

Workshop: A Stack and Queue System

Programming in C · Chapter 11: Dynamic Memory, Linked Lists, Stacks, and QueuesSection 11.7 · lesson 77 of 786 min · free with a free account

← Dynamic Linked List OperationsNext lesson: Workshop: A Menu-Driven Linked List Manager →

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

In this lesson

A menu-driven program that runs an array stack and a circular queue.

  • Organize a program into stack, queue, and menu modules that return success codes
  • Compute a circular queue's next free slot from front and count
  • Compare command words with strcmp instead of the == operator
  • Handle bad input by reporting it and skipping the rest of the line

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 (805 words). Read along, or search it.

The Challenge

A Prize Shelf and a Racer Line

The Starlight Arcade has two kinds of waiting. The prize shelf is a stack: the last prize placed on top is the first one taken. The line at the Racer machine is a queue: whoever came first plays first. Priya builds one program that runs both. You type push, pop, enq and deq. And when something goes wrong, it says so in plain words.

Program Plan

Modules That Return Success or Failure

First, the plan. Each data structure gets its own header file, called a module: a small file that does one job. The menu program only calls the modules' functions. It never touches their arrays directly. Every function that can fail returns one for success and zero for failure, so the menu decides what to print. The rooms are tiny on purpose, two slots for the stack and three for the queue, so the limits show up after only a few commands.

Stack Module

A Two-Slot Array Stack

stack dot h is the array stack from 11.4, with room for two. top counts the items, and it's also the next free slot. stack_push refuses when top equals STACK_MAX. Otherwise, it writes at top, and then adds one. stack_pop refuses at zero. Otherwise, it subtracts one first, and then reads. stack_show prints from the top down, or the word empty.

Queue Module

Front Plus Count Replaces Rear

queue dot h is a circular queue, as in 11.5, with a twist. It keeps front and count, but no rear. The next free slot is always front plus count, wrapped with the remainder. That one formula replaces rear. dequeue reads at front, moves front forward with the wrap, and lowers the count.

Quick Check

Finding the Next Free Slot

Quick check. Three tickets join, two are served, and ticket 4 joins. Now front is 2, and count is 2. Ticket 5 joins next. Which slot does it land in? Pause and predict. Build and run: ticket 5 is in slot 1. front plus count is 2 plus 2, which is 4. And 4, remainder 3, is 1. Slot 0 holds ticket 4, which wrapped around before it, and slot 2 still holds 3, the next one to be served.

Menu Loop

Reading Commands Word by Word

menu dot c includes both modules. The loop prints a prompt, and reads one word with scanf, fifteen characters at most. If scanf doesn't return one, the input has ended, so the loop breaks. That's how it stops even without a quit. strcmp picks the command. It returns zero when the two strings are equal, as in 7.6. push and enq need a number, so they call read_number. If the number is missing, it prints a message. Then skip_line throws away the rest of that line, with the getchar loop from 7.7. Otherwise, the leftover text would be read as the next command. Any other word prints Unknown command, and also skips the line.

Common Mistake

Comparing Strings With Double Equals

One common mistake: writing cmd equals equals push. That compares two addresses, not two texts, so it's almost never true. Clang warns about it, even without dash Wall: result of comparison against a string literal is unspecified. So put strcmp back, and compare its result with zero. Now the build is clean. With both modules and the menu in place, it's time to type some commands.

Stack Test

Overflow and Underflow Messages

Now try the stack. Sam's favorite test: push more than fits, and pop more than there is. push 10 and push 20 fit. push 30 is refused: stack overflow, 30 not added. pop gives 20, then 10. The third pop has nothing left: stack underflow, nothing to pop. A good program answers nonsense politely. Priya's first version printed a random number here, because it popped without checking top.

Queue Test

A Full Queue and Two Typos

Now the queue, which holds three. Tickets 1, 2 and 3 join, and ticket 4 is refused: queue full. deq serves ticket 1, the first to arrive. Then 5 joins, and show prints both structures. The stack is empty, and the queue reads 2, 3, 5. Ticket 5 wrapped around into slot 0, but it's still last in line. Last, two typos. jump is an unknown command, and push abc has no number. Each gets one message, and the program carries on until quit.

Quick Check

Two Numbers on One Line

Quick check. Sam types push 5 6, two numbers on one line, and presses Enter. Think about the two scanf calls in menu dot c. What happens? Pause and predict. Run it. push reads one number, 5, and pushes it. The 6 is still waiting in the input. So the loop's next scanf reads 6 as the next command word: unknown command, 6. And show confirms the stack holds just 5. Nothing crashed, and nothing jammed. Each bad word got one clear message.

Key Takeaways

Modules, Messages, and Clean Input

To sum up. Split the program into modules: a stack, a queue, and a menu loop. Functions return one or zero, and the menu prints the message. Compare words with strcmp, never with equals equals. After bad input, skip the rest of the line, so one typo can't jam the program.

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: A Stack and Queue System

How do you implement a circular queue without a rear index?
Keep front and count, and compute the next free slot as (front + count) % CAP. With 3 slots, front at 2, and count at 2, the next ticket goes into slot (2 + 2) % 3, which is 1. Dequeue reads at front, moves front forward with the same wrap, and lowers the count, so one formula replaces the rear index.
Why can't you compare strings with == in C?
Using == on two strings compares their addresses, not their characters, so cmd == "push" is almost never true even when the user typed push. Clang warns that the result of a comparison against a string literal is unspecified. Use strcmp(cmd, "push") == 0 instead, because strcmp returns zero when the two strings are equal.
How do you build a command menu loop in C?
Read one word per pass with scanf and a width limit, such as %15s for a 16-character buffer, and leave the loop when scanf does not return 1, which means input has ended. Compare the word with strcmp to choose a command, read any number the command needs, and print a message for unknown words. Each operation returns 1 or 0, so the menu decides what to print.
Why should a C menu program skip the rest of the line after bad input?
Leftover text stays in the input and would be read as the next command. If push expects a number but finds abc, the program should print a message and then discard the rest of the line, for example with a getchar loop that stops at the newline. Otherwise one typo can set off a chain of confusing errors instead of one clear message.

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 →