Types and variables in C exercises — master printf, scanf and operators
Types and variables in C exercises are where printf, scanf and the type system stop feeling foreign. You’ve seen the theory and built three complete programs. Now it’s time to solve challenges on your own in Fedora.
In this article you’ll find four exercises across three levels — from a BMI calculator to geometric shapes, number bases and a final challenge that combines everything.
As always: try to solve it in gedit, compile with gcc, use the hint if stuck for more than 10 minutes, and compare with the commented solution.
Before starting:
cd ~/GCID/IC2/Labs mkdir exercises_types cd exercises_types
Table of Contents
Types and variables in C exercises — Basic Level
Exercise 1 — BMI calculator
Write a C program that asks for a person’s name, weight in kg and height in metres, and calculates their Body Mass Index (BMI). Show the result with the standard classification.
BMI formula: weight / (height × height)
Classification:
BMI < 18.5 → Underweight 18.5 ≤ BMI < 25.0 → Normal weight 25.0 ≤ BMI < 30.0 → Overweight BMI ≥ 30.0 → Obese
The output should look like this:
=== BMI CALCULATOR === Name: Sergio Weight (kg): 72 Height (m): 1.78 --- Results for Sergio --- Weight: 72.00 kg Height: 1.78 m BMI: 22.72 Classification: Normal weight
💡 Hints:
- Use
char name[50],double weight,double height - BMI =
weight / (height * height)— both operands are already double so no cast needed - Use
%lfin scanf for doubles,%.2fin printf - Use
if/else if/elsefor the classification
Exercise 2 — Geometric shapes calculator
Write a C program that asks for the dimensions of three shapes and calculates their area and perimeter. All measurements are doubles.
Formulas:
Circle: area = PI × r² perimeter = 2 × PI × r
Rectangle: area = base × height perimeter = 2 × (base + height)
Triangle: area = (base × height) / 2
perimeter = a + b + c (three sides)
Use const double PI = 3.14159265;
The output should look like this:
=== GEOMETRIC SHAPES === --- Circle --- Radius: 5 Area: 78.54 Perimeter: 31.42 --- Rectangle --- Base: 4 Height: 6 Area: 24.00 Perimeter: 20.00 --- Triangle --- Base: 3 Height: 4 Side A: 3 Side B: 4 Side C: 5 Area: 6.00 Perimeter: 12.00
💡 Hints:
- Declare
const double PI = 3.14159265;at the top of main - For
r²useradius * radius— no power operator in C - All values are
double— use%lfto read,%.2fto print - No cast needed since all operands are already double
Types and variables in C exercises — Intermediate Level
Exercise 3 — Number base converter
Write a C program that reads a positive integer and shows it in binary, octal and hexadecimal — using only printf format specifiers (no manual conversion needed).
Then extract and show each digit of the decimal number using only integer arithmetic (/ and %).
The output should look like this:
=== NUMBER BASE CONVERTER === Enter a positive integer: 255 --- Base conversions --- Decimal: 255 Binary: Not directly supported (see note) Octal: 377 Hexadecimal: ff Uppercase: FF --- Digit extraction (decimal) --- Number: 255 Units: 5 Tens: 5 Hundreds: 2 Sum of digits: 12 --- Character analysis --- ASCII code 65 is the character: A Your number as ASCII: %c is not printable (255 > 127)
💡 Hints:
%oprints octal,%xprints lowercase hex,%Xprints uppercase hex- Binary has no printf specifier in standard C — just note it’s not directly available
- Digit extraction: units =
n % 10, tens =(n / 10) % 10, hundreds =n / 100 - For the character check:
if (number >= 32 && number <= 126)→ printable ASCII
Types and variables in C exercises — Final Challenge
Exercise 4 — Complete invoice
Write a C program that generates a product invoice. It reads: company name, product name, quantity (int), unit price (double), discount percentage (double) and tax rate (double). It calculates and displays a complete formatted invoice.
=== INVOICE GENERATOR ===
Company name: Sergio Learns
Product: Programming Course
Quantity: 3
Unit price (€): 49.99
Discount (%): 10
Tax rate (%): 21
============================================
INVOICE
============================================
Company: Sergio Learns
Product: Programming Course
--------------------------------------------
Quantity: 3
Unit price: 49.99 €
--------------------------------------------
Subtotal: 149.97 €
Discount (10%): -15.00 €
After discount: 134.97 €
Tax (21%): 28.34 €
--------------------------------------------
TOTAL: 163.31 €
============================================
Per unit after tax: 54.44 €
💡 Hints:
- Use
chararrays for company and product names - Subtotal =
quantity * unit_price— cast quantity to double:(double)quantity * unit_price - Discount amount =
subtotal * discount_pct / 100.0 - Tax amount =
after_discount * tax_rate / 100.0 - For the separator line use
printf("%-44s\n", "----...")or justprintf("----...\n") - Per unit after tax =
total / quantity— cast quantity to double
Commented solutions
Solution Exercise 1
#include <stdio.h>
int main() {
char name[50];
double weight, height, bmi;
printf("=== BMI CALCULATOR ===\n\n");
printf("Name: ");
scanf("%s", name);
printf("Weight (kg): ");
scanf("%lf", &weight);
printf("Height (m): ");
scanf("%lf", &height);
bmi = weight / (height * height);
printf("\n--- Results for %s ---\n", name);
printf("Weight: %.2f kg\n", weight);
printf("Height: %.2f m\n", height);
printf("BMI: %.2f\n", bmi);
printf("Classification: ");
if (bmi < 18.5)
printf("Underweight\n");
else if (bmi < 25.0)
printf("Normal weight\n");
else if (bmi < 30.0)
printf("Overweight\n");
else
printf("Obese\n");
return 0;
}
Solution Exercise 2
#include <stdio.h>
int main() {
const double PI = 3.14159265;
double radius, base, height, side_a, side_b, side_c;
double area, perimeter;
printf("=== GEOMETRIC SHAPES ===\n");
/* Circle */
printf("\n--- Circle ---\n");
printf("Radius: ");
scanf("%lf", &radius);
area = PI * radius * radius;
perimeter = 2 * PI * radius;
printf("Area: %.2f\n", area);
printf("Perimeter: %.2f\n", perimeter);
/* Rectangle */
printf("\n--- Rectangle ---\n");
printf("Base: ");
scanf("%lf", &base);
printf("Height: ");
scanf("%lf", &height);
area = base * height;
perimeter = 2 * (base + height);
printf("Area: %.2f\n", area);
printf("Perimeter: %.2f\n", perimeter);
/* Triangle */
printf("\n--- Triangle ---\n");
printf("Base: ");
scanf("%lf", &base);
printf("Height: ");
scanf("%lf", &height);
printf("Side A: ");
scanf("%lf", &side_a);
printf("Side B: ");
scanf("%lf", &side_b);
printf("Side C: ");
scanf("%lf", &side_c);
area = (base * height) / 2.0;
perimeter = side_a + side_b + side_c;
printf("Area: %.2f\n", area);
printf("Perimeter: %.2f\n", perimeter);
return 0;
}
Solution Exercise 3
#include <stdio.h>
int main() {
int n;
printf("=== NUMBER BASE CONVERTER ===\n\n");
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("\n--- Base conversions ---\n");
printf("Decimal: %d\n", n);
printf("Octal: %o\n", n);
printf("Hexadecimal: %x\n", n);
printf("Uppercase: %X\n", n);
printf("\n--- Digit extraction (decimal) ---\n");
printf("Number: %d\n", n);
if (n >= 0 && n <= 9999) {
int units = n % 10;
int tens = (n / 10) % 10;
int hundreds = (n / 100) % 10;
int thousands = n / 1000;
int digit_sum = units + tens + hundreds + thousands;
printf("Units: %d\n", units);
if (n >= 10) printf("Tens: %d\n", tens);
if (n >= 100) printf("Hundreds: %d\n", hundreds);
if (n >= 1000) printf("Thousands: %d\n", thousands);
printf("Sum of digits: %d\n", digit_sum);
}
printf("\n--- Character analysis ---\n");
printf("ASCII code %d is the character: ", n);
if (n >= 32 && n <= 126)
printf("%c\n", (char)n);
else
printf("(not printable)\n");
return 0;
}
Solution Exercise 4
#include <stdio.h>
int main() {
char company[50];
char product[50];
int quantity;
double unit_price, discount_pct, tax_rate;
double subtotal, discount_amount, after_discount, tax_amount, total;
printf("=== INVOICE GENERATOR ===\n\n");
printf("Company name: ");
scanf("%s", company);
printf("Product: ");
scanf("%s", product);
printf("Quantity: ");
scanf("%d", &quantity);
printf("Unit price (€): ");
scanf("%lf", &unit_price);
printf("Discount (%%): ");
scanf("%lf", &discount_pct);
printf("Tax rate (%%): ");
scanf("%lf", &tax_rate);
/* Calculations */
subtotal = (double)quantity * unit_price;
discount_amount = subtotal * discount_pct / 100.0;
after_discount = subtotal - discount_amount;
tax_amount = after_discount * tax_rate / 100.0;
total = after_discount + tax_amount;
/* Invoice output */
printf("\n============================================\n");
printf(" INVOICE\n");
printf("============================================\n");
printf("Company: %s\n", company);
printf("Product: %s\n", product);
printf("--------------------------------------------\n");
printf("Quantity: %6d\n", quantity);
printf("Unit price: %7.2f €\n", unit_price);
printf("--------------------------------------------\n");
printf("Subtotal: %7.2f €\n", subtotal);
printf("Discount (%.0f%%): %7.2f €\n", discount_pct, -discount_amount);
printf("After discount: %7.2f €\n", after_discount);
printf("Tax (%.0f%%): %7.2f €\n", tax_rate, tax_amount);
printf("--------------------------------------------\n");
printf("TOTAL: %7.2f €\n", total);
printf("============================================\n");
printf("Per unit after tax: %.2f €\n", total / (double)quantity);
return 0;
}
Visualise with Python Tutor
Python Tutor supports C — select C from the language dropdown. Paste this code to see how C handles types in memory:
#include <stdio.h>
int main() {
int a = 7;
int b = 2;
double result_int = a / b;
double result_cast = (double)a / b;
char c = 'A';
int ascii = c;
printf("%f vs %f\n", result_int, result_cast);
printf("%c = %d\n", c, ascii);
return 0;
}
Step through it and observe three things. a / b gives 3 even though you’re storing it in a double — integer division happens before the assignment. (double)a / b converts a to 7.0 before dividing, giving 3.5. And char c = 'A' with int ascii = c shows that the same value 65 can be read as a character or a number depending on the type you use to interpret it.
Cheat sheet — Types and variables in C
/* ============================================
CHEAT SHEET — Types and Variables in C
Sergio Learns · sergiolearns.com
============================================ */
/* BASIC TYPES */
int i = 5; /* integer — 4 bytes */
double d = 3.14; /* decimal — 8 bytes (use this) */
float f = 3.14f; /* decimal — 4 bytes (less precise) */
char c = 'A'; /* single character — 1 byte */
char s[50] = "text"; /* string — array of char */
long l = 9000000L; /* large integer */
/* DECLARATION RULES */
int x; /* declared, garbage value inside */
int x = 5; /* declared with value */
int x, y, z; /* multiple, same type */
const double PI = 3.14; /* constant — cannot change */
#define MAX 100 /* preprocessor constant — no type */
/* PRINTF FORMAT SPECIFIERS */
printf("%d\n", i); /* int */
printf("%f\n", d); /* double (6 decimal places) */
printf("%.2f\n", d); /* double, 2 decimal places */
printf("%e\n", d); /* scientific notation */
printf("%c\n", c); /* char */
printf("%s\n", s); /* string */
printf("%ld\n", l); /* long */
printf("%o\n", i); /* octal */
printf("%x\n", i); /* hexadecimal lowercase */
printf("%X\n", i); /* hexadecimal uppercase */
printf("%%\n"); /* literal % sign */
/* PRINTF WIDTH AND PADDING */
printf("%10d\n", i); /* right-aligned, width 10 */
printf("%-10d\n", i); /* left-aligned, width 10 */
printf("%010d\n", i); /* zero-padded, width 10 */
printf("%7.2f\n", d); /* width 7, 2 decimal places */
/* SCANF — CRITICAL RULES */
scanf("%d", &i); /* int — & required */
scanf("%lf", &d); /* double — %lf NOT %f */
scanf("%f", &f); /* float */
scanf("%c", &c); /* char — & required */
scanf(" %c", &c); /* space before %c skips whitespace */
scanf("%s", s); /* string — NO & needed */
/* TYPE CASTING */
(double)a / b /* cast before dividing for decimal result */
(int)3.99 /* → 3 (truncates, does NOT round) */
(char)65 /* → 'A' */
(int)'A' /* → 65 */
/* INTEGER DIVISION TRAP */
int a = 7, b = 2;
a / b /* → 3 (drops decimal) */
(double)a / b /* → 3.5 (cast first) */
7.0 / 2 /* → 3.5 (literal double) */
/* OPERATORS */
a + b a - b a * b /* standard */
a / b /* integer division if both int */
a % b /* remainder (NOT percentage) */
a++ a-- ++a --a /* increment/decrement */
a += b a -= b a *= b a /= b a %= b
/* CHAR AND ASCII */
char c = 'A'; /* 'A' = 65 in ASCII */
printf("%c", c); /* prints: A */
printf("%d", c); /* prints: 65 */
printf("%c", c + 1); /* prints: B */
char lower = c + 32; /* uppercase to lowercase: A→a */
/* COMMON ERRORS */
/* 1. Missing ; at end of statement */
/* 2. Missing & in scanf (except strings) */
/* 3. %f instead of %lf in scanf for double */
/* 4. Integer division: 7/2 = 3 not 3.5 */
/* 5. %% to print literal %, not % */
/* 6. Single quotes for char, double for strings */
/* COMPILE AND RUN */
/* gcc program.c -o program -Wall */
/* ./program
