Workshop: Variables, Data Types, and Formatted Output

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

Workshop: Variables, Data Types, and Formatted Output

Programming in C · Chapter 4: Conditional Logic, Decision Structures, and Practical ApplicationsSection 4.1 · lesson 19 of 788 min · free with a free account

← Building Your First C ProgramNext lesson: Relational Operators: Testing Relationships Between Values →

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

In this lesson

Build a player card, prize calculator and receipt with formatted output.

  • Choose char, int, long or double to match each piece of data
  • Format aligned output with printf widths, precision and the minus flag
  • Use integer division and remainder to split a total
  • Cast one operand to get a decimal result from two ints

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

The Task

A Neat Player Card

A new player walks up to the Starlight Arcade counter and asks for a player card. The card shows five facts: an initial, a level, a token count, a best score, and a win rate. Priya, who builds the arcade's software, has to print it. And it had better look neat, because a messy card makes the whole arcade look sloppy.

Workshop Method

Plan, Code, Run, Improve

In this workshop you grow three programs: the card, a prize calculator, and a receipt. Each one goes around the same loop. Plan the facts and a type for each, code a few lines, run it and read the output, then improve. Run after every small step, and a mistake can only hide in the few lines you just wrote.

Planning Types

A Type for Each Fact

Plan first. Each fact needs a type that matches what it is. The initial is one character, so it's a char, written in single quotes. Level and tokens are whole numbers, so they're ints. The best score, one million two hundred fifty thousand, is big. A long is guaranteed to hold it, though a typical int could too. The win rate has a decimal point, so it's a double. Then each type gets its matching printf code: %c, %d, %ld, and %f.

First Run

Six Decimals and Ragged Columns

Step one is only declare, assign, and print. Compile it with warnings turned on. No messages means a clean build. Then run it. It works. But the win rate shows as 62.500000. A plain %f always prints six decimal places. And nothing lines up. The labels have different lengths, so each number starts wherever its label ends.

Neater Output

Widths, Alignment and a Bonus

Step two adds a bonus and neater printing. First, tokens equals tokens plus fifty. That assignment replaces the old value with a new one. Now the format codes. %-12s pads a label to twelve characters, left-aligned. %7d pads a number to seven, right-aligned. And %6.1f keeps one decimal, in six characters. Two percent signs in a row print one real percent sign. A single one would start another format code. Run it. Tokens shows 390, because the bonus was added before printing. And the box lines up, because every row is exactly 24 characters wide.

Quick Check

Leo and 42 in Width Six

Quick check, with a new line of code. A three-letter name goes in a width of six, and a two-digit number in a width of six. Square brackets surround each value, and in the options each dot stands for one space. What does it print? Pause and predict. Build it and run it. It prints Leo followed by three spaces, and then four spaces before forty-two. The minus sign pads the name on the right, so it's left-aligned. With no minus, the number is padded on the left. Six characters each time: three letters plus three spaces, and two digits plus four spaces.

Program Two

Prizes, Leftovers and Value

Program two is a prize calculator. A prize costs 25 tokens, and Sam, the arcade's tester, has 137. Whole-number division counts the full bundles: 137 divided by 25 is 5 prizes. The remainder operator, the percent sign, counts what's left over: 12 tokens. The program also reports how close those twelve are to the next prize, and what all the tokens are worth, at a quarter each.

Worked Example

A Cast for the Progress Percent

Here's the code. It asks for the number with scanf, so this time the player types it in. Prizes is tokens divided by the prize cost. Leftover is the remainder of that same division. Dollars multiplies by the token value, which is a double, so that answer is a double too. Line 14 has the one tricky part. The word double, in parentheses, is a cast. It turns leftover into a double before dividing. Run it, and Sam types 137. Five prizes, 12 left, 48 percent of the way to the next, and worth $34.25.

Bug Hunt

Progress Drops to Zero

Now skip the cast, and watch what happens. Delete it, rebuild, and run again with the same 137. Progress to next is now 0.0 percent. Nothing else changed. Leftover and prize cost are both ints, so C divides whole numbers. Twelve divided by twenty-five is zero, before anything is stored. Storing the answer in a double doesn't rescue a division that already happened. So put the cast back, on one side, before the slash.

Program Three

A Receipt With Aligned Columns

Program three is a receipt. Sam buys two pretzels at $3.50, and one soda at $2.25. The arcade adds 8 percent tax. Every price and quantity goes in a variable. Then the program works out each line total, the subtotal, and the tax. Now the printing. To make columns line up, give every column a fixed width in the format. The item name is twelve wide, left-aligned. Quantity is four, price is nine, and the line total is ten, each right-aligned. The bottom lines use a label twenty-five wide: the first three columns added up, twelve plus four plus nine. One more detail. The percent sign in the tax label sits in an argument, not in the format, so it prints as it is. Run it. Seven dollars plus two twenty-five is nine twenty-five. Eight percent of that is seventy-four cents, so the total is nine ninety-nine.

Quick Check

Three Divided by Four

Quick check. This new program works out three divided by four, and stores the answer in a double named share. Then it prints share with two decimals. What appears? Pause and predict. Build and run it. It prints zero point zero zero. Three and four are both ints, so C divides whole numbers and gets zero. Only then is that zero turned into a double. The double on the left can't reach back into the division. The smallest fix is one decimal point. Three point zero divided by four gives zero point seven five. A cast on one side works too.

Key Takeaways

Types, Widths and Small Steps

To sum up. Pick the type from the fact: char for one character, int or long for whole numbers, double for decimals. Widths line things up. A minus sign means left-aligned, a point one keeps one decimal, and two percent signs print one. Dividing two ints throws away the fraction, so cast one side first. And grow every program in small steps: plan, code, run, improve. Something to try. Change the prize cost to 40. Before you run it, work out by hand what 137, 40, and 39 tokens give.

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: Variables, Data Types, and Formatted Output

How do you print a percent sign with printf?
Write two percent signs, %%, in the format string to print one percent sign. A single % starts a format specifier, so printf would look for a value to fill it. For example, printf("%.1f%%", 48.0) prints 48.0%. A percent sign inside a string passed as an argument, rather than in the format, prints as it is, because printf interprets only the format string.
How do you line up columns of output in C?
Give every column a fixed width in the printf format. Text such as %-12s is padded to twelve characters and left-aligned, while numbers such as %4d or %9.2f are right-aligned by default. Because each field always takes the same width, rows line up. For a total row, a label width equal to the earlier columns added together keeps the total under its column.
How do you calculate prizes and leftover tokens with division in C?
Use integer division for the whole prizes and the remainder operator for the leftovers. With 137 tokens and prizes costing 25, 137 / 25 gives 5 prizes and 137 % 25 gives 12 tokens left. To show progress toward the next prize as a percentage, cast first: (double)12 / 25 * 100 gives 48.0, while 12 / 25 alone gives 0.
Which C data type should store a score like 1,250,000?
A long is guaranteed to hold 1,250,000, because the C standard requires a long to have at least 32 bits, while an int is guaranteed only 16. On most current systems an int is 32 bits and holds it too. Print a long with %ld. For other facts, a single character fits a char printed with %c, and a decimal such as a win rate fits a double.

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 →