🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Solved C Programming Exercises
Seven complete programs for this free embedded C course
This lecture closes Chapter 4 of our free C programming course with seven complete, working programs. Each one takes input from the user, uses the operators you learned in this chapter, and prints a formatted result. Writing small programs like these is the fastest way to turn operator rules into real embedded C programming skill, because every sensor, timer and motor routine you will write later follows the same read, compute, print pattern.
This free C tutorial gives you the problem, a short plan, the full code, the exact build commands and the real output. Every program was compiled with GCC 13.3 using -std=c11 -Wall -Wextra and run with the inputs shown.
What You Will Learn
- How to turn a problem statement into input, process and output steps
- Temperature conversion without the classic
9/5integer-division bug - Area and perimeter of a circle using
doubleand a named constant - Printing one number in decimal, octal and hexadecimal with
%u,%oand%X - Using the modulus operator
%on a five digit number - Choosing between a sum and a difference with the ternary operator
- Simple interest and percentage calculations with correct type conversion
- Checking the return value of
scanfso bad input does not break your program
Prerequisites
You should know variables, data types, printf and scanf, and the arithmetic, relational, conditional and assignment operators from this chapter. You need GCC or Clang to compile the programs.
Solving C Exercises Step by Step in This Free C Programming Course
Every program in this lecture follows one pattern. Learning it once saves you from staring at a blank editor.
| Step | What you decide | Example from this lecture |
|---|---|---|
| Read | Variable types matching the format specifier | %f with float, %lf with double, %d with int |
| Validate | What counts as bad input | scanf must return the number of values requested |
| Compute | Operator order and conversions | celsius * 9.0f / 5.0f + 32.0f |
| How many decimals and what labels | %.2f for money and temperature |
Why check scanf?
scanf returns how many items it read. If it returns less than you asked for, the variables were not filled and your calculation would use garbage. A single if keeps every program below safe.
Exercise 1: Celsius to Fahrenheit Program
Problem: read a temperature in Celsius and print it in Fahrenheit. The formula is F = C x 9 / 5 + 32. The only trap is writing 9 / 5, which is integer division and gives 1.
#include <stdio.h>
int main(void)
{
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
if (scanf("%f", &celsius) != 1) {
printf("Invalid input\n");
return 1;
}
fahrenheit = celsius * 9.0f / 5.0f + 32.0f; /* 9.0f keeps it floating-point */
printf("%.2f C = %.2f F\n", celsius, fahrenheit);
return 0;
}
gcc -std=c11 -Wall -Wextra -o p1 p1.c
./p1
Enter temperature in Celsius: 37
37.00 C = 98.60 F
The 9/5 Bug in Action
Here is what happens if you write the formula the way it looks in a maths book:
#include <stdio.h>
int main(void)
{
float celsius = 37.0f;
float wrong = celsius * (9 / 5) + 32; /* 9/5 is integer division = 1 */
float right = celsius * 9.0f / 5.0f + 32;
printf("wrong = %.2f, right = %.2f\n", wrong, right);
return 0;
}
./p1bug
wrong = 69.00, right = 98.60
Body temperature of 37 C came out as 69 F, because (9 / 5) was evaluated as integer division before it was multiplied. Using 9.0f forces floating-point arithmetic, and the compiler gives you no warning, so only testing finds this.
Exercise 2: Circle Area and Perimeter
Problem: read the radius and print area and perimeter. The formulas are area = pi x r x r and perimeter = 2 x pi x r. Use double for better precision and a #define for the constant, so it appears only once in the program.
#include <stdio.h>
#define PI 3.14159265
int main(void)
{
double radius, area, perimeter;
printf("Enter radius: ");
if (scanf("%lf", &radius) != 1 || radius < 0) {
printf("Invalid radius\n");
return 1;
}
area = PI * radius * radius;
perimeter = 2 * PI * radius;
printf("Area = %.3f\n", area);
printf("Perimeter = %.3f\n", perimeter);
return 0;
}
./p2
Enter radius: 5.5
Area = 95.033
Perimeter = 34.558
Use %lf with scanf for double
printf accepts %f for both float and double, but scanf does not. Reading a double needs %lf. Using %f there stores a wrong value and is a very common beginner bug.
Exercise 3: Decimal to Octal and Hexadecimal
Problem: read a decimal number and print it in octal and hexadecimal. C does not need any conversion logic, because printf converts for you using the %o and %X specifiers. Using unsigned int avoids confusing results for negative numbers.
#include <stdio.h>
int main(void)
{
unsigned int n;
printf("Enter a decimal number: ");
if (scanf("%u", &n) != 1) {
printf("Invalid input\n");
return 1;
}
printf("Decimal : %u\n", n);
printf("Octal : %o\n", n);
printf("Hexadecimal : %X\n", n);
printf("With prefix : %#o and %#X\n", n, n);
return 0;
}
./p3
Enter a decimal number: 255
Decimal : 255
Octal : 377
Hexadecimal : FF
With prefix : 0377 and 0XFF
| Specifier | Meaning | Output for 255 |
|---|---|---|
%u | Unsigned decimal | 255 |
%o | Octal, no prefix | 377 |
%x / %X | Hex lower or upper case | ff / FF |
%#o / %#X | Adds the 0 or 0X prefix | 0377 / 0XFF |
In embedded C programming you will print register values in hex all the time, so %X and %#X are worth remembering.
Exercise 4: Remainder of a Five Digit Number
Problem: read a five digit number and print the remainder when it is divided by 3. The modulus operator % does the work. To print a literal percent sign in printf, write %%.
#include <stdio.h>
int main(void)
{
int n;
printf("Enter a five digit number: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input\n");
return 1;
}
printf("%d %% 3 = %d\n", n, n % 3);
return 0;
}
./p4
Enter a five digit number: 48271
48271 % 3 = 1
echo abc | ./p4
Enter a five digit number: Invalid input
A five digit int fits easily in 16 bits or more, but int is only guaranteed 16 bits by the standard. If you port the code to a small microcontroller where int is 16 bits, 48271 no longer fits, so use long or int32_t for portable code.
Exercise 5: Sum or Difference With the Ternary Operator
Problem: read two numbers. If the first is greater than the second, print their sum; otherwise print their difference. Use the conditional operator ?: so the choice is one expression.
#include <stdio.h>
int main(void)
{
int a, b, result;
printf("Enter two numbers: ");
if (scanf("%d %d", &a, &b) != 2) {
printf("Invalid input\n");
return 1;
}
result = (a > b) ? (a + b) : (a - b);
printf("Result = %d\n", result);
return 0;
}
./p5
Enter two numbers: 9 4
Result = 13
./p5
Enter two numbers: 3 8
Result = -5
The parentheses around (a + b) and (a - b) are not required, but they make the intent obvious and protect you if you later assign inside the branches.
Exercise 6: Simple Interest Calculator
Problem: read the principal, the yearly rate and the number of years, then print the simple interest. The formula is interest = principal x rate x years / 100.
#include <stdio.h>
int main(void)
{
float principal, rate, years, interest;
printf("Enter principal, rate (%%) and years: ");
if (scanf("%f %f %f", &principal, &rate, &years) != 3) {
printf("Invalid input\n");
return 1;
}
interest = principal * rate * years / 100.0f;
printf("Simple interest = %.2f\n", interest);
printf("Total amount = %.2f\n", principal + interest);
return 0;
}
./p6
Enter principal, rate (%) and years: 10000 7.5 3
Simple interest = 2250.00
Total amount = 12250.00
Everything is float, so there is no integer division problem. Dividing by 100.0f rather than 100 keeps the whole expression in floating point even if you later change some variables to int.
Exercise 7: Total and Percentage of Five Subjects
Problem: read marks in five subjects and print the total and the percentage. This one shows type conversion clearly, because total is an int but percentage needs decimals.
#include <stdio.h>
#define SUBJECTS 5
int main(void)
{
int m1, m2, m3, m4, m5, total;
float percentage;
printf("Enter marks in %d subjects (out of 100 each): ", SUBJECTS);
if (scanf("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5) != 5) {
printf("Invalid input\n");
return 1;
}
total = m1 + m2 + m3 + m4 + m5;
percentage = (float)total * 100.0f / (SUBJECTS * 100);
printf("Total = %d / %d\n", total, SUBJECTS * 100);
printf("Percentage = %.2f%%\n", percentage);
return 0;
}
./p7
Enter marks in 5 subjects (out of 100 each): 78 85 69 92 71
Total = 395 / 500
Percentage = 79.00%
The cast (float)total converts before the multiplication. Without it, total * 100 / 500 would be integer division and would drop any fractional part, which is wrong for a total like 396.
| Version | Expression | Result for total 396 |
|---|---|---|
| Integer only | total * 100 / 500 | 79 |
| With cast | (float)total * 100.0f / 500 | 79.20 |
Operators Used in Each Exercise
| Exercise | Main operators | Key idea |
|---|---|---|
| 1. Celsius to Fahrenheit | * / + | Floating-point constants |
| 2. Circle | * | double and %lf |
| 3. Octal and hex | none (format only) | %o, %X, %#X |
| 4. Remainder | % | Escape %% in printf |
| 5. Sum or difference | ?: > + - | Conditional expression |
| 6. Simple interest | * / | Float arithmetic |
| 7. Percentage | + * / cast | Convert before dividing |
Common Mistakes in the Free C Programming Course
| Mistake | Result | Fix |
|---|---|---|
9 / 5 instead of 9.0f / 5.0f | Temperature wrong (69 F instead of 98.6 F) | Use a floating-point constant |
%f with scanf for a double | Wrong value stored | Use %lf |
Ignoring the return value of scanf | Uninitialised variables used | Check it equals the number of items |
Forgetting %% in printf | Percent sign missing or format warning | Write %% |
| Integer division before cast | Fraction lost | Cast first, or use a float constant |
int for a large number on a 16 bit target | Overflow | Use long or int32_t |
Best Practices for Free C Programming Course Exercises
- Use named constants (
#define PI,#define SUBJECTS 5) instead of repeating magic numbers. - Choose
doubleunless memory is tight; many small microcontrollers have no floating-point unit, so measure before using floats in firmware. - Validate input before using it, even in a classroom program.
- Compile with
-Wall -Wextraand treat every warning as a bug to explain. - Test with at least three inputs: a normal value, a boundary value and a bad value.
Practice Challenges
- Extend Exercise 1 to also convert Fahrenheit back to Celsius and show both results.
- Change Exercise 2 to reject a negative radius with a message, then print the diameter as well.
- Change Exercise 4 to print the quotient and the remainder together.
- Extend Exercise 7 to read five marks and print the average and the highest mark using the ternary operator.
Interview Questions on These Programs
Why does celsius * (9 / 5) give a wrong answer?
Because 9 / 5 is integer division and evaluates to 1 before the multiplication, so the scale factor is lost.
What is the difference between %f and %lf in scanf?
%f reads a float and %lf reads a double. printf accepts %f for both because arguments are promoted to double.
How do you print a percent sign with printf?
Write %% in the format string.
What does scanf return and why does it matter?
It returns the number of items successfully read. Checking it prevents using variables that were never assigned.
When should you cast before dividing?
When both operands are integers but you need a fractional result, cast one operand to a floating-point type before the division.
Summary and Key Takeaways
- Every small program follows read, validate, compute, print.
- Floating-point constants such as
9.0fprevent hidden integer division. %lfis needed forscanfwithdouble;%oand%Xprint octal and hex.%gives the remainder, and%%prints a percent sign.?:picks between two expressions in one line.- Checking the return value of
scanfmakes your programs safe.
Conclusion: Finish Chapter 4 of the Free C Programming Course
You have finished Chapter 4 of this free C programming course. Operators and expressions are the grammar of C, and these seven programs showed them working together on real input. Re-type each program instead of copying it, break it on purpose, and read the compiler warnings. When you are ready, continue with the next chapter of our free embedded C course and keep building toward real microcontroller code.
Frequently Asked Questions
Is this free C tutorial suitable for beginners in embedded systems?
Yes. This free C programming course starts from operators and basic input and output, which are the foundation of embedded C programming.
Why use float and not int for the temperature program?
Fahrenheit values usually have decimals. Integer arithmetic would drop the fractional part and the 9/5 factor.
How do I print a number in binary in C?
Standard printf has no binary specifier. Print each bit using shifts and the bitwise AND operator, which you will learn in a later chapter.
Why does my percentage program print 79.00 as 79?
That happens with integer division or with the %d format. Cast to float and print with %.2f.
What should I do if scanf fails?
Print an error message and return a non-zero value from main, as the programs in this lecture do.
Where can I find more exercises in this free embedded C course?
Each chapter of the EmbeddedPathashala C course ends with practice programs and interview questions.
Keep Going With the Free C Programming Course
Every lecture on EmbeddedPathashala is free. Practise the programs on your own machine, then move on to the next lecture to keep building real embedded C skills.

2 Comments