🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Quadratics and Operator-Free Arithmetic
Chapter 6, Functions, programming exercises 4 to 7: a series sum, a quadratic equation program in C, an uppercase converter and multiplication, quotient and remainder built without the usual operators. Free C programming course.
A quadratic equation program in C looks like a school maths problem, yet it teaches three habits that matter in every firmware project: choose the branch before computing, protect against degenerate input, and respect floating-point behaviour. This lecture of our free C programming course solves four exercises together. We sum a series, write a quadratic equation program in C that handles real, repeated and complex roots, convert lowercase characters to uppercase with no library help, and finally build multiplication, quotient and remainder functions without using the *, / and % operators, the way a tiny processor without hardware multiply or divide has to.
What You Will Learn
- How to read a series with an irregular start and write a loop that handles each term.
- How to design a quadratic equation program in C around the discriminant.
- Why you must watch for
a == 0and why comparing doubles for equality is risky. - How ASCII lets you convert case with arithmetic or with a single bit mask.
- How to multiply and divide using only addition, subtraction and shifts.
- How these ideas appear in embedded C programming on small cores.
Prerequisites
You need loops, if / else if / else, floating-point variables and a basic grasp of ASCII codes. For the quadratic solver, link the maths library with -lm when you use GCC, for example gcc -std=c11 -Wall -Wextra solver.c -o solver -lm.
Summing a Series Whose First Terms Are Special
The fourth exercise gives the series 1 + 1/2 + 1/4 + 1/9 + 1/16 and so on, and asks for the sum up to n terms. Read the terms carefully. The first is 1, the second is 1/2, and from the third onward each term is one over a perfect square: 1/4 is one over 2 squared, 1/9 is one over 3 squared, 1/16 is one over 4 squared. So the third term uses the base 2, the fourth uses 3, and in general term t uses the base t minus 1.
#include <stdio.h>
/* Terms: 1, 1/2, 1/4, 1/9, 1/16, ... (from the third term on: 1/(t-1)^2) */
double series_sum(int terms)
{
double sum = 0.0;
for (int t = 1; t <= terms; t++) {
if (t == 1) {
sum += 1.0;
} else if (t == 2) {
sum += 0.5;
} else {
double base = t - 1; /* double, so no integer division */
sum += 1.0 / (base * base);
}
}
return sum;
}
int main(void)
{
int counts[] = {5, 10, 1000, 100000};
for (int i = 0; i < 4; i++)
printf("%6d terms -> %.6f\n", counts[i], series_sum(counts[i]));
return 0;
}
5 terms -> 1.923611
10 terms -> 2.039768
1000 terms -> 2.143934
100000 terms -> 2.144924
Five terms give 1 + 0.5 + 0.25 + 0.111111 + 0.0625, which is 1.923611, exactly what the program prints. As the term count grows, the total settles near 2.1449, because the square-reciprocal part of the series converges to a known constant, the square of pi divided by six. You can verify the neighbourhood of that value yourself with the 100,000 term run.
sum += 1 / (t * t); with integer variables, every term from the second on becomes 0, because 1 divided by a larger integer truncates to zero. Make one operand a double, as the program does with 1.0 and a double base.
Quadratic Equation Program in C: Real, Repeated and Complex Roots
The fifth exercise asks for the roots of a x squared plus b x plus c equals zero. The quantity b*b - 4*a*c, called the discriminant, decides everything. A positive value gives two real roots, zero gives one repeated root, and a negative value gives a pair of complex roots whose real part is minus b over 2a and whose imaginary part is the square root of the negated discriminant over 2a.
Choosing the branch from the discriminant
a equals zero
Not a quadratic. Solve the linear equation, or report that no equation exists.
Discriminant positive
Two different real roots from the standard formula.
Zero or negative
Zero gives one repeated root. Negative gives a conjugate complex pair.
#include <stdio.h>
#include <math.h>
void solve_quadratic(double a, double b, double c)
{
if (a == 0.0) { /* degenerates to bx + c = 0 */
if (b == 0.0)
printf("no equation: a and b are both zero\n");
else
printf("linear: x = %.4f\n", -c / b);
return;
}
double disc = b * b - 4.0 * a * c;
double twoa = 2.0 * a;
if (disc > 0.0) {
double root = sqrt(disc);
printf("two real roots: %.4f and %.4f\n",
(-b + root) / twoa, (-b - root) / twoa);
} else if (disc == 0.0) {
printf("one repeated root: %.4f\n", -b / twoa);
} else {
double re = -b / twoa;
double im = sqrt(-disc) / twoa;
printf("complex roots: %.4f +/- %.4fi\n", re, im);
}
}
int main(void)
{
solve_quadratic(1, -3, 2);
solve_quadratic(1, 2, 1);
solve_quadratic(1, 2, 5);
solve_quadratic(0, 4, -8);
return 0;
}
two real roots: 2.0000 and 1.0000
one repeated root: -1.0000
complex roots: -1.0000 +/- 2.0000i
linear: x = 2.0000
The four calls exercise every branch: the equation x squared minus 3x plus 2 has roots 2 and 1, x squared plus 2x plus 1 has a repeated root of minus 1, x squared plus 2x plus 5 has complex roots minus 1 plus or minus 2i, and the last call has a equal to zero, so it degenerates into 4x minus 8 equals zero.
| Coefficients (a, b, c) | Discriminant | Result |
|---|---|---|
| 1, -3, 2 | 1 | Two real roots, 2 and 1 |
| 1, 2, 1 | 0 | One repeated root, -1 |
| 1, 2, 5 | -16 | Complex, -1 plus or minus 2i |
| 0, 4, -8 | not used | Linear, x = 2 |
Floating-Point Cautions in a Quadratic Equation Program in C
Testing disc == 0.0 works for these tidy inputs, but in real measurement data a discriminant that should be zero may come out as a tiny positive or negative number. Production code compares against a small tolerance instead. A second subtlety appears when b squared is far larger than 4ac: subtracting two nearly equal numbers in the formula loses precision. Numerical libraries avoid that by computing the larger-magnitude root first and deriving the other from the product of the roots. For a school exercise the direct formula is fine, but it is worth knowing why library solvers look different.
Converting Lowercase to Uppercase Without a Library
The sixth exercise asks for a function that accepts a lowercase character and returns its uppercase form. In ASCII, the letter a has code 97 and A has code 65, so the distance is always 32. Subtracting 'a' and adding 'A' shifts any lowercase letter into the uppercase block without memorising numbers. Because 32 is a power of two, the same conversion is also a single bit operation: clearing bit 5.
#include <stdio.h>
char to_upper_ascii(char ch)
{
if (ch >= 'a' && ch <= 'z')
return (char)(ch - 'a' + 'A'); /* distance between cases is 32 */
return ch; /* leave everything else alone */
}
char to_upper_mask(char ch)
{
if (ch >= 'a' && ch <= 'z')
return (char)(ch & ~0x20); /* clear bit 5 */
return ch;
}
int main(void)
{
const char *text = "embedded c 2026!";
for (const char *p = text; *p != '\0'; p++)
putchar(to_upper_ascii(*p));
putchar('\n');
for (const char *p = text; *p != '\0'; p++)
putchar(to_upper_mask(*p));
putchar('\n');
return 0;
}
EMBEDDED C 2026!
EMBEDDED C 2026!
Both functions give the same result. They guard the conversion with a range test, because applying the bit mask to a digit or punctuation mark would corrupt it. The space, digits and exclamation mark pass through unchanged, as the output shows. Standard code would normally call toupper from ctype.h, which also respects locale rules, but a hand-written version is handy on tiny systems and is a frequent interview question.
Multiplication, Quotient and Remainder Without * / %
The seventh exercise forbids the three operators and asks for functions mult, quo and rem. These are not only puzzles. Some small microcontroller cores have no hardware divider, and a few have no multiplier, so the compiler’s runtime library implements them with exactly these ideas.
Repeated addition and the faster shift-and-add
Multiplication is repeated addition: 6 times -7 is minus 7 added six times. The sign is handled separately by remembering whether exactly one operand was negative. Repeated addition needs as many steps as the second number is large, which is slow for big values. Shift-and-add reads the second number bit by bit. For each set bit, it adds the first number, which has been shifted left once per bit position already passed. Thirteen times eleven works because 11 is binary 1011: add 13, add 26 for the second bit and add 104 for the fourth bit, giving 143.
Shift-and-add for 13 times 11
Quotient and remainder by repeated subtraction
Division by repeated subtraction counts how many times the divisor fits into the dividend. When the loop stops, what is left over is the remainder. The two functions share the same loop; one returns the count, the other returns what remains.
#include <stdio.h>
/* Multiplication by repeated addition; handles negative operands. */
int mult_add(int a, int b)
{
int negative = 0;
int total = 0;
if (a < 0) { a = -a; negative = !negative; }
if (b < 0) { b = -b; negative = !negative; }
for (int i = 0; i < b; i++)
total += a;
return negative ? -total : total;
}
/* Faster: shift-and-add, the way a small CPU without a multiplier does it. */
unsigned mult_shift(unsigned a, unsigned b)
{
unsigned result = 0;
while (b != 0) {
if (b & 1u)
result += a;
a <<= 1;
b >>= 1;
}
return result;
}
/* Non-negative dividend, positive divisor; returns -1 for a zero divisor. */
int quo_sub(int dividend, int divisor)
{
int q = 0;
if (divisor <= 0)
return -1;
while (dividend >= divisor) {
dividend -= divisor;
q++;
}
return q;
}
int rem_sub(int dividend, int divisor)
{
if (divisor <= 0)
return -1;
while (dividend >= divisor)
dividend -= divisor;
return dividend;
}
int main(void)
{
printf("mult_add(-7, 6) = %d\n", mult_add(-7, 6));
printf("mult_shift(13, 11) = %u\n", mult_shift(13, 11));
printf("quo_sub(100, 7) = %d\n", quo_sub(100, 7));
printf("rem_sub(100, 7) = %d\n", rem_sub(100, 7));
printf("quo_sub(9, 0) = %d\n", quo_sub(9, 0));
return 0;
}
mult_add(-7, 6) = -42
mult_shift(13, 11) = 143
quo_sub(100, 7) = 14
rem_sub(100, 7) = 2
quo_sub(9, 0) = -1
The outputs confirm that 100 equals 14 times 7 plus 2. The function returns minus one for a zero divisor, a convention that must be documented because minus one is not a valid quotient for non-negative input. A robust interface might instead return a status code and write the answer through a pointer.
| Operation | Technique | Steps needed |
|---|---|---|
| Multiply by repeated addition | Add a, b times | About b |
| Multiply by shift-and-add | Check each bit of b | Number of bits, for example 32 |
| Quotient by subtraction | Subtract until too small | About the quotient |
| Remainder by subtraction | Same loop, return the leftover | About the quotient |
Real-World Uses of a Quadratic Equation Program in C
- Control and filtering: solving a quadratic appears in motion planning and in curve-fit calibration of sensors.
- Protocol parsing: case conversion is used when matching AT commands or HTTP headers that ignore case.
- Tiny CPUs: runtime libraries for cores without multiply or divide instructions use shift-based algorithms very similar to the ones above.
- Fixed-point maths: understanding shifts makes scaling by powers of two a natural tool for DSP code.
Common Mistakes and Troubleshooting
| Mistake | Effect | Fix |
|---|---|---|
Forgetting -lm when linking sqrt | Linker error: undefined reference | Add -lm at the end of the command |
Dividing by 2 * a when a is zero | Infinity or NaN | Check for a == 0 first |
| Integer division in series terms | Terms become 0 | Use 1.0 and a double operand |
| Applying the case mask to every character | Digits and symbols are corrupted | Check the range 'a' to 'z' first |
| Subtracting forever with a zero divisor | Infinite loop | Reject divisors of zero or below |
| Negative operands to the subtraction helpers | Wrong or endless loops | Handle signs or document the contract |
Best Practices, Performance and Security
Best practices
- Handle degenerate cases before applying a general formula.
- Compare floating-point values with a tolerance when exact zero matters.
- Document the allowed input range of every arithmetic helper.
- Prefer the library routine unless you are on a core where you must supply your own.
Performance: the shift-and-add multiplier needs a fixed number of steps no matter how large the numbers are, while repeated addition grows with the value, which can be a million iterations on a bad input. The quotient loop has the same weakness, so production code uses shift-and-subtract long division. Security: a zero divisor reaching a hand-written division loop becomes a denial-of-service hole, because the loop never ends. Validate every divisor that comes from outside the device.
Quadratic Equation Program in C: Key Takeaways
- Read series terms one at a time; the pattern may start late.
- The discriminant selects the branch in a quadratic equation program in C.
- ASCII case differs by 32, which is bit 5.
- Multiplication is repeated addition, and shift-and-add makes it fast.
- Quotient and remainder fall out of one subtraction loop.
Each exercise in this lecture looks small, but together they cover branch selection, floating-point care, character arithmetic and low-level number crunching, the toolkit of embedded C programming. Try extending the solver to read coefficients from the keyboard, and rewrite the quotient function to use shifts. In the final lecture of this chapter we solve the recursive exercises and finish with a quiz and interview questions.
Frequently Asked Questions
How does a quadratic equation program in C decide the type of roots?
It computes the discriminant b squared minus 4ac. Positive means two real roots, zero means one repeated root and negative means complex roots.
Why do I get an undefined reference to sqrt?
The maths library is not linked. Add -lm at the end of the GCC command.
Why is the difference between lowercase and uppercase letters 32?
ASCII places the uppercase letters at 65 to 90 and the lowercase ones at 97 to 122, so each pair differs by exactly 32, which is bit 5.
Can I multiply without the * operator in C?
Yes, by repeated addition or by shift-and-add. The second method is much faster for large values.
Why return -1 for division by zero?
It is a simple error marker for non-negative results. Larger systems prefer a status code so that every valid value remains available.
Does the series in exercise 4 converge?
Yes. The sum approaches roughly 2.1449 as the number of terms grows.
One More Lecture to Finish Chapter 6
Next: recursive digit sum, combinations and printing a number in words, plus a quiz and interview questions. All of it free in our embedded C course.

2 Comments