Video Link
Exercises
Section 1: Variables — Boxes That Hold Data
Variables are named containers for data. Every variable in C has a name, a type, and a value. These exercises will help you get comfortable declaring, initializing, and using variables.
Exercise 1.1 — Declaring and Initializing
Write a program that stores and prints information about yourself.
- Declare an
intvariable calledageand set it to your age. - Declare a
floatvariable calledheight_cmand set it to your height in centimeters. - Declare a
charvariable calledinitialand set it to the first letter of your name. - Print all three values using
printf. Your output should look like:Age: 25 Height: 175.50 cm Initial: C
Hint: Each
printfcall needs a matching format specifier:%dfor int,%ffor float,%cfor char.
Exercise 1.2 — Variable Naming Rules
Identify which of the following variable names are valid in C. For each invalid name, explain why and write a corrected version.
- Evaluate each name:
first name,2ndValue,_counter,my-variable,totalCost,float,MAX_SIZE,x - For each invalid name: write what rule it breaks and suggest a valid alternative.
- Bonus: Which of the valid names follow good naming conventions, and which are technically valid but poor style?
Hint: C variable names must start with a letter or underscore, contain only letters/digits/underscores, and cannot be reserved keywords.
Exercise 1.3 — Swap Two Variables
Without looking up how to do it, figure out how to swap the values of two variables.
- Declare two
intvariables:a = 10andb = 25. - Print their values:
Before swap: a = 10, b = 25. - Swap the values so that
acontains 25 andbcontains 10. You will need a third variable. - Print again:
After swap: a = 25, b = 10. - Why can’t you just write
a = b; b = a;without a third variable? Write a comment in your code explaining this.
Hint: Think about what happens step-by-step when you write
a = b. What happens to the original value ofa?
Exercise 1.4 — The Constant Variable
Explore the difference between a variable and a constant.
- Declare
int pi_approx = 3andfloat pi_precise = 3.14159f. - Now declare a constant:
const float PI = 3.14159f; - Try to change
PIafter declaring it (e.g.PI = 4.0f;). What error does the compiler give you? Write it down. - Calculate the circumference of a circle with radius 7.5 using
circumference = 2 * PI * radius. Print the result. - Why is using a named constant better than writing
3.14159directly in your formula? Write a comment explaining.
Exercise 1.5 — Memory Size Exploration
C variables take up physical space in memory. Investigate how much.
- Use the
sizeof()operator to print the size (in bytes) of each type:char,int,float,double,long,long long. - Format your output as a table:
Type: int Size: 4 bytes - Calculate: if you have an array of 1,000
doubles, how many bytes of memory would it use? Print this. - Research question (write your answer as a comment): why might
sizeof(int)differ between a 32-bit and 64-bit system?
Hint:
sizeof()can be used like a function:sizeof(int)orsizeof(myVariable). Use%zuas the format specifier for its return type.
Section 2: Input & Output — Talking to Users
printf() sends data to the screen. scanf() reads data from the keyboard. Together they let your program have a conversation. These exercises build comfort with both — and with the quirks that catch beginners off guard.
Exercise 2.1 — Formatted Output
printf() is more powerful than it looks. Explore its formatting options.
- Print an integer right-aligned in a field 10 characters wide: use
%10dwith value42. - Print a float with exactly 2 decimal places: use
%.2fwith value3.14159. - Print a string left-aligned in a field 15 characters wide: use
%-15s. - Combine them: print a “receipt” with item name, quantity, and price. Each column should be aligned.
Hint: Format specifiers can include width and precision:
%8.2fmeans “width 8, 2 decimal places.”
Exercise 2.2 — Basic User Input
Build a program that asks the user for their initials and age, then greets them.
- Prompt
Enter your first initial:and read a singlecharusingscanf("%c", &initial); - Prompt
Enter your age:and read anint. - Print a greeting:
Hello, C! You are 25 years old.(replacingCand25with the user’s input) - Run your program and test it. What happens if someone enters letters when you ask for age?
Hint: Always put
&before the variable name inscanf()— except for strings/char arrays. NOTE: We will talk about scanf much later, we should avoid it for the most part in production code
Exercise 2.3 — Simple Calculator
Build an interactive two-number calculator.
- Ask the user to enter two floating-point numbers.
- Print the result of addition, subtraction, multiplication, and division — all four.
- Format each result to 2 decimal places.
- Handle the case where the user enters 0 for the second number: before dividing, check if it’s zero and print
Error: division by zeroinstead of crashing. - Sample output:
10.00 + 3.00 = 13.00 10.00 - 3.00 = 7.00 10.00 * 3.00 = 30.00 10.00 / 3.00 = 3.33
Exercise 2.4 — Receipt Printer
Build a formatted store receipt that looks professional.
- Ask the user to enter 3 items. For each: read a product name (single word), quantity (
int), and price per unit (float). - Calculate the subtotal for each item (quantity × price).
- Print a formatted receipt with columns:
Item,Qty,Unit Price,Subtotal— all aligned. - Print a line of dashes as a separator, then the total at the bottom.
- Bonus: Add an 8.5% tax calculation and print
TaxandGrand Totallines.
Hint: Use
%-20sfor left-aligned strings,%5dfor right-aligned integers, and%8.2ffor currency amounts.
Section 3: Operators — Math and Logic
C’s operators let you compute, compare, and combine. The key insight: = means “assign”, not “equals”. == means “is equal to”. This trips up almost every beginner. These exercises will make the distinction second nature.
Exercise 3.1 — Arithmetic Operators
Practice all five arithmetic operators, including the one beginners forget about: %
- Given
int a = 17andint b = 5, calculate and print:a+b,a-b,a*b,a/b, anda%b. - Before running: predict each result on paper. Then check — were you surprised by any?
- Now try with
float a = 17.0fandfloat b = 5.0f. How doesa/bchange? - Practical use: Write code that determines whether a given number is even or odd using the
%operator.
Hint: Integer division truncates:
17/5is3in C, not3.4. The remainder17%5gives you what’s left over:2.
Exercise 3.2 — Comparison and Logical Operators
Comparison operators return 1 (true) or 0 (false) in C. Explore this.
- Declare
int x = 10andint y = 20. Print the result of:x == y,x != y,x < y,x > y,x <= 10,y >= 20. - Now test logical operators. Print the result of:
(x < y) && (x > 5),(x > y) || (x == 10),!(x == y). - Predict each result before running. Write your predictions as comments.
- Tricky question: What does
printf("%d", x = 5);print, and why is this different fromx == 5? Write your answer as a comment.
Exercise 3.3 — Compound Assignment Operators
Rewrite operations using shorthand compound assignment operators.
- Start with
int score = 100. Using only compound assignment operators (+=,-=,*=,/=,%=), produce the sequence:100, 115, 110, 220, 55, 5. Print the value after each operation. - Write the same sequence without compound operators (using full expressions like
score = score + 15). Verify you get the same results. - Which version is easier to read? Write a comment with your opinion.
- Bonus: What do the increment (
++) and decrement (--) operators do? Testi++vs++iand explain any difference.
Hint:
i++(post-increment) returns the value first, then increments.++i(pre-increment) increments first, then returns the value.
Exercise 3.4 — Operator Precedence
Just like in math, C evaluates operators in a specific order. Get it wrong and you’ll get the wrong answer silently.
- Without running the code, evaluate each expression for
a=6,b=4,c=2:2 + 3 * 4a + b * ca * b + c * aa / b + ca % b * c
- Now run the code and check your answers. Write corrections as comments for any you got wrong.
- Add parentheses to the third expression so that the addition happens before the multiplication. What’s the new result?
- Takeaway: When in doubt, use parentheses. Write a comment explaining why explicit parentheses are good practice.
Exercise 3.5 — Building an Expression Evaluator
Use your knowledge of all operators to solve a real problem.
A movie theater charges $12.50 per adult ticket and $8.00 per child ticket. There’s a 10% group discount if the total number of tickets is 10 or more.
- Ask the user how many adult tickets and child tickets they want.
- Calculate: subtotal, whether discount applies (use a comparison:
totalTickets >= 10), discount amount (if applicable), and final total. - Print a detailed breakdown. Format all money values to 2 decimal places.
- Test your program with:
- 3 adults + 2 children (no discount)
- 8 adults + 4 children (discount applies)
Section 4: Control Flow & Loops
Control flow is how programs make decisions and repeat actions. Without it, programs can only do one thing, in one order, every time. With it, programs can respond to input, repeat work, and solve complex problems.
Exercise 4.1 — If/Else Chains
Write a grade classifier program.
- Ask the user to enter a numeric score (0–100).
- Using
if/else if/else, print the letter grade: A (90–100), B (80–89), C (70–79), D (60–69), F (below 60). - Also print a message:
Passing!orNeeds improvement.depending on whether the grade is D or above. - Add input validation: if the score is below 0 or above 100, print
Invalid scoreand skip the grade calculation.
Exercise 4.2 — Switch Statements
Build a text-based day-of-week program using switch.
- Ask the user to enter a number 1–7 (1 = Monday, 7 = Sunday).
- Use a
switchstatement to print the day name. - Also print whether it’s a weekday or weekend.
- Use the
defaultcase to handle invalid input. - Bonus: Rewrite the same logic using
if/else. Which feels more readable for this particular problem?
Hint: Group cases together for weekday/weekend:
case 1: case 2: ... case 5:(all fall through to the same code).
Exercise 4.3 — While Loop — Input Validation
Use a while loop to keep asking until the user enters valid input.
- Ask the user to enter a number between 1 and 10.
- If they enter something outside that range, print
Invalid. Try again.and ask again. - Keep looping until they enter a valid number.
- Once valid input is received, print
You entered: Xand exit. - Test your program by deliberately entering bad values first. Does it behave correctly?
Hint: The loop condition should check whether the input is invalid. The loop body should re-prompt and re-read.
Exercise 4.4 — For Loops — Patterns and Sequences
For loops are perfect when you know exactly how many times to repeat.
- Print the first 10 perfect squares (1, 4, 9, 16 … 100). One per line, formatted as:
1^2 = 1 - Print a multiplication table for a number the user enters (show 1× through 10×).
- FizzBuzz: print numbers 1 to 50. For multiples of 3 print
Fizz, for multiples of 5 printBuzz, for multiples of both printFizzBuzz, otherwise print the number. - Bonus: Using a nested for loop, print a right triangle of asterisks 5 rows tall.
Exercise 4.5 — Number Guessing Game
Combine everything: variables, input, comparison, and loops.
- Set a secret number:
int secret = 42; - Use a
whileloop to keep asking the user to guess. - After each guess, print
Too high!,Too low!, orCorrect!as appropriate. - Count the number of guesses and print it when they succeed:
You got it in 5 guesses! - Add a maximum of 10 guesses — if they use all 10 without guessing correctly, reveal the answer.
- Bonus: Use
rand()andsrand(time(NULL))to generate a random secret number between 1 and 100 each run.
Exercise 4.6 — Collatz Conjecture
One of math’s most famous unsolved problems — and a perfect loop exercise.
- Ask the user to enter any positive integer.
- Apply the Collatz rule: if the number is even, divide by 2. If odd, multiply by 3 and add 1.
- Keep applying the rule and printing each value until you reach 1.
- Count the number of steps taken.
- Print:
Starting from X, it took N steps to reach 1. - Test with: 6 (should take 8 steps), 27 (takes 111 steps!), and any large number of your choice.
Note: The Collatz conjecture says this always reaches 1, but mathematicians have never proven it for all numbers. Your code will empirically verify it for small inputs.
Section 5: Types & Type Conversion — When Types Meet
C is a typed language — every value has a type, and mixing types has consequences. Sometimes C converts silently (implicit conversion). Sometimes you convert deliberately (explicit casting). Getting this wrong produces bugs that are notoriously hard to find.
Exercise 5.1 — Integer Division Surprise
Integer division is one of the most common sources of bugs for C beginners.
- Predict, then print:
7/2,7/2.0,7.0/2,7.0/2.0. Are all four results different? - Calculate the average of three test scores:
int s1=85, s2=92, s3=78. Store in afloat avg. - First try:
float avg = (s1 + s2 + s3) / 3;— print the result. Is it correct? - Fix it by casting:
float avg = (float)(s1 + s2 + s3) / 3;— print again. What changed? - Write a comment explaining why the first version produced the wrong answer.
Hint: When C divides two ints, it throws away the decimal part before storing the result — even if you’re storing into a float.
Exercise 5.2 — Implicit Type Conversion Chain
When different types meet in an expression, C promotes to the “wider” type. Trace what happens.
- For each expression, predict the type and value of the result, then verify with
printf:5 + 2.0'A' + 1(int)3.9(float)5 / 2(int)(7.9 + 0.5)
- Expression
'A' + 1may surprise you. In C,'A'is stored as the integer 65 (its ASCII value). What does'A' + 1equal? - Expression
(int)(7.9 + 0.5)is a classic rounding trick. What does it do and why?
Hint: C’s type promotion rules:
char→int→long→float→double. The “wider” type wins.
Exercise 5.3 — Type Casting in Practice
Explicit casting: you tell C what type conversion you want.
- Write a program that converts a temperature from Celsius to Fahrenheit:
F = (9/5) * C + 32. - First write it with all integer math. Test with C = 100. What do you get? (It will be wrong.)
- Fix it: cast appropriately so the arithmetic works correctly. 100°C should give 212.0°F.
- Also implement Fahrenheit to Celsius:
C = (F - 32) * 5 / 9. - Ask the user to enter a temperature and direction of conversion, then print the result to 1 decimal place.
Exercise 5.4 — Integer Overflow
What happens when a number gets too big for its type? Something surprising.
- Declare
int max = 2147483647(the maximum value for a 32-bit int on most systems). Printmax. Then printmax + 1. What do you see? Write down the result and explain it. - Now try:
unsigned int umax = 4294967295;Printumax, thenumax + 1. - Declare
char c = 127(max for signed char). Printc, thenc+1. - Write a comment explaining the concept of overflow and why it’s dangerous in real programs.
- Research question: What famous software bug was caused by integer overflow?
Hint: Numbers wrap around when they exceed their type’s maximum — like an odometer clicking from 99999 to 00000.
Exercise 5.5 — 0.1 + 0.2 ≠ 0.3
One of programming’s most famous surprises: floating point numbers are not exact.
- Print the result of
0.1 + 0.2. Use%.20fto see 20 decimal places. Is it exactly0.3? - Now write:What prints?
if (0.1 + 0.2 == 0.3) { printf("Equal"); } else { printf("Not equal"); } - Fix it: instead of checking exact equality, check if the difference is smaller than a small epsilon:(You’ll need
fabs(result - 0.3) < 0.0001#include <math.h>) - Write a comment explaining why floats can’t represent
0.1exactly (think binary fractions — just like1/3has no exact decimal representation).
Note: This is not a bug in your code or in C. It’s a fundamental property of how floating point numbers are stored in binary.
Exercise 5.6 — The Type Detective
Analyze and fix a buggy program. Each bug involves a type error.
- Bug 1:
int total = 0; total = total + 3.7 + 2.1; printf("%d", total);— why does this print an unexpected value, and what’s the correct approach? - Bug 2:
char grade = 'A'; printf("%d", grade);— this actually compiles fine, but what does it print and why? - Bug 3:
int x = 1000000; int y = 1000000; printf("%d", x * y);— what happens and why? - Bug 4:
float price = 19.99f; int cents = price * 100;— iscentsexactly1999? Check and explain. - For each bug: write the corrected version and a comment explaining the fix.