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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Relational Operators: Testing Relationships Between Values →← Building Your First C ProgramNext lesson: Relational Operators: Testing Relationships Between Values →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
How do you line up columns of output in C?
How do you calculate prizes and leftover tokens with division in C?
Which C data type should store a score like 1,250,000?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →