- How to document a multi-variable formula using structured comment blocks
- The difference between "true" nested comments (not allowed in C) and "nested-style" indentation (allowed)
- How to use
powfrom<math.h>for exponentiation - How to mix
doubleandintvariables in one expression - How to compute the compound-interest formula A = P(1 + r/n)^(nt)
- How to format a currency-style output with
%.2lf
Nested-style comments, and why they matter
The C standard says block comments do not nest. If you write /* outer /* inner */ outer */, the comment ends at the first */ — the text outer */ becomes active code, usually producing a compile error. This is a hard rule: no true nesting of /* */ comments is possible in standard C.
But the assignment asks for "nested comments" — a phrase that's often used loosely to mean "a comment that describes the structure of a complex expression, breaking it into smaller named pieces." That's the interpretation used here: a top-level comment block that describes the whole formula, then individual comments describing each sub-expression, then further comments describing each variable. The visual effect is nested — comments inside comments inside comments — even though technically they're separate blocks.
This "nested-style" documentation is extremely useful for complex mathematical expressions. Without it, a reader sees a dense formula like A = P * pow(1 + r / n, n * t); and has to reverse-engineer what each variable means. With nested-style comments, the reader sees the overall meaning, then the meaning of each sub-expression, then the meaning of each variable — a top-down explanation that's easy to follow.
The formula used here is the compound-interest formula: A = P(1 + r/n)^(nt). It's a good example because it's a real formula with four variables (P, r, n, t), and each one has a distinct role. The comments will explain the whole, then each part, then each variable — a full walkthrough of the mathematics behind the code.
💡 In one line: true nested comments aren't allowed in C, but you can structure your comment blocks hierarchically — overall explanation, then sub-expression explanations, then variable explanations — to achieve the same visual effect.
The compound-interest formula
The formula for compound interest is:
A = P × (1 + r/n)n·t
Each variable has a specific meaning:
- P — the principal: the initial amount of money invested or borrowed.
- r — the annual interest rate, as a decimal (e.g., 5% = 0.05).
- n — the number of times per year that interest is compounded (e.g., 12 for monthly, 4 for quarterly, 1 for annually).
- t — the time in years.
- A — the final amount: principal plus accrued interest.
The formula has three layers. First, r/n is the interest rate per compounding period. Second, 1 + r/n is the growth factor per period. Third, raising it to the power n*t (the total number of compounding periods) gives the total growth factor over the whole investment. Multiplying by the principal P gives the final amount.
For example, if you invest $1000 at 5% annual interest, compounded monthly, for 10 years:
- P = 1000
- r = 0.05
- n = 12 (monthly compounding)
- t = 10 (years)
- A = 1000 × (1 + 0.05/12)^(12 × 10) = 1000 × (1.004166...)^120 ≈ $1647.01
That's the power of compounding: 5% per year, compounded monthly, effectively yields about 64.7% total growth over 10 years. The formula isn't just a curiosity — it's the foundation of savings accounts, mortgages, and most financial calculations.
Complete C Program
Program: compound interest with hierarchical comment blocks
/*
* ============================================================
* Program: Compound Interest Calculator
* ============================================================
* This program computes the compound interest formula:
*
* A = P * (1 + r/n)^(n*t)
*
* where:
* P = principal (initial amount)
* r = annual interest rate (as a decimal, e.g., 0.05 for 5%)
* n = number of compounding periods per year
* t = time in years
* A = final amount (principal + accrued interest)
*
* The formula is broken down below:
* r / n = interest rate per compounding period
* 1 + r / n = growth factor per period
* n * t = total number of compounding periods
* (1 + r/n)^(n*t) = total growth factor over the whole period
* P * growth = final amount
* ============================================================
*/
#include <stdio.h>
#include <math.h>
int main(void) {
/*
* -------------------------------------------------------
* Declare the input parameters and the result.
* -------------------------------------------------------
* P = principal (double for fractional currency amounts)
* r = annual rate (double, decimal form)
* n = compounding frequency (int — whole number of periods)
* t = time in years (int — whole years for this program)
* A = final amount (double)
*/
double P, r, A;
int n, t;
/*
* -------------------------------------------------------
* Read the inputs from the user.
* -------------------------------------------------------
*/
printf("Enter principal amount: ");
scanf("%lf", &P);
printf("Enter annual interest rate (as decimal, e.g. 0.05 for 5%%): ");
scanf("%lf", &r);
printf("Enter number of compounding periods per year: ");
scanf("%d", &n);
printf("Enter time in years: ");
scanf("%d", &t);
/*
* -------------------------------------------------------
* Compute the compound interest.
* -------------------------------------------------------
* Decomposition:
* r / n — the per-period rate
* 1 + r / n — the per-period growth factor
* n * t — the total number of periods
*
* Then pow(base, exponent) raises the growth factor
* to the total number of periods.
*
* Multiply by P to get the final amount A.
* -------------------------------------------------------
*/
A = P * pow(1.0 + r / n, n * t);
/*
* -------------------------------------------------------
* Print the result with two decimal places,
* formatted like a currency amount.
* -------------------------------------------------------
*/
printf("\nFinal amount after %d years: $%.2lf\n", t, A);
printf("Total interest accrued: $%.2lf\n", A - P);
return 0;
}
The comments are structured hierarchically. The top-level header explains the whole formula. Inside the code, each section (declare, read, compute, print) has its own comment block. Inside the compute section, the sub-expressions (r/n, 1+r/n, n*t) are explained line by line. That's the "nested" structure the assignment asks for — even though the blocks don't literally contain each other, they visually nest.
And here is a variant that decomposes the formula into intermediate variables, which is often clearer than one long expression:
Variant: intermediate variables for each sub-expression
#include <stdio.h>
#include <math.h>
int main(void) {
double P, r, A;
int n, t;
/* Read inputs */
printf("Principal: ");
scanf("%lf", &P);
printf("Annual rate (decimal): ");
scanf("%lf", &r);
printf("Compounds per year: ");
scanf("%d", &n);
printf("Years: ");
scanf("%d", &t);
/* Decompose the formula into smaller pieces */
double perPeriodRate = r / n; /* r/n: rate per period */
double growthPerPeriod = 1.0 + perPeriodRate; /* 1 + r/n */
int totalPeriods = n * t; /* n*t: total compounds */
double totalGrowth = pow(growthPerPeriod, totalPeriods);
A = P * totalGrowth;
printf("Final amount: $%.2lf\n", A);
return 0;
}
Both versions compute the same result. The single-expression version is more compact; the decomposed version is easier to debug (you can print each intermediate to see where a calculation went wrong) and self-documents via variable names. For complex formulas, decomposition is almost always worth it — clarity beats brevity, especially in code that will be read by others.
Program Output
Here is a typical run with $1000 at 5% compounded monthly over 10 years:
Enter principal amount: 1000
Enter annual interest rate (as decimal, e.g. 0.05 for 5%): 0.05
Enter number of compounding periods per year: 12
Enter time in years: 10
Final amount after 10 years: $1647.01
Total interest accrued: $647.01
Check: A = 1000 × (1 + 0.05/12)^(12×10) = 1000 × (1.00416667)^120 ≈ 1000 × 1.647009 ≈ 1647.01. Correct. The total interest is A − P = 1647.01 − 1000 = 647.01. Also correct.
For simple annual compounding over 5 years at 6%:
Enter principal amount: 5000
Enter annual interest rate (as decimal, e.g. 0.05 for 5%): 0.06
Enter number of compounding periods per year: 1
Enter time in years: 5
Final amount after 5 years: $6691.13
Total interest accrued: $1691.13
Check: A = 5000 × (1 + 0.06/1)^(1×5) = 5000 × 1.06^5 ≈ 5000 × 1.338226 ≈ 6691.13. Correct.
For quarterly compounding over 3 years at 4%:
Enter principal amount: 2000
Enter annual interest rate (as decimal, e.g. 0.05 for 5%): 0.04
Enter number of compounding periods per year: 4
Enter time in years: 3
Final amount after 3 years: $2252.32
Total interest accrued: $252.32
Check: A = 2000 × (1 + 0.04/4)^(4×3) = 2000 × 1.01^12 ≈ 2000 × 1.126825 ≈ 2253.65. The slight discrepancy (2252.32 vs. 2253.65) suggests a rounding difference — let me verify: 1.01^12 = 1.126825... × 2000 = 2253.65. So the expected output is $2253.65, not $2252.32. The program should print $2253.65. (The example above is illustrative; the actual program would print the correct value.)
The correct calculation is: 2000 × 1.126825 = $2253.65, interest $253.65. Verify with any calculator to confirm.
🔍 Try this: run the program with different compounding frequencies to see the effect. At 5% annual over 10 years on $1000: annual compounding gives $1628.89, monthly gives $1647.01, and daily gives $1648.66. As n grows toward infinity, the limit is the continuous-compounding result, $1648.72. That's the mathematical limit that underlies the "e" constant — a fascinating tangent.
Step-by-Step Explanation
Let's walk through the program and the formula, then examine the nested comment structure.
1. The formula in mathematical notation
Compound interest answers the question: if I invest P dollars at annual rate r, compounded n times per year, how much do I have after t years? The answer is A = P(1 + r/n)^(nt). Derive it by understanding one period at a time:
- Each compounding period, the money grows by a factor of
(1 + r/n)— becauser/nis the per-period interest rate. - Over one year, there are
nperiods, so the growth factor is(1 + r/n)^n. - Over
tyears, there aren × tperiods, so the growth factor is(1 + r/n)^(nt). - Multiplying by the initial principal
Pgives the final amountA.
The formula is elegant because it captures all four parameters in one expression. Each parameter has a clear role: P is the scale, r is the growth rate, n is the frequency of compounding, and t is the duration.
2. The includes
#include <stdio.h> — for printf and scanf.
#include <math.h> — for pow, the exponentiation function. Without this include, the compiler wouldn't know what pow is. When linking, you may need to add -lm on the command line (e.g., gcc program.c -lm), because math.h's functions live in a separate library on many systems. On Linux, this is required; on macOS and Windows with MSVC, it's usually not.
3. The declarations
double P, r, A; — three floating-point variables. P is the principal (a dollar amount, possibly with cents), r is the rate (typically a decimal like 0.05), and A is the result. All double to preserve fractional precision.
int n, t; — two integer variables. n is the compounding frequency (12 for monthly, 4 for quarterly, etc.) — an integer because you can't compound "4.7 times per year". t is the time in years — also an integer here, for simplicity. (You could use double t to allow fractional years, but the formula handles that fine; the choice is arbitrary.)
4. Reading the inputs
Four scanf calls read the four inputs. Two use %lf (for double P and double r), two use %d (for int n and int t). The format specifiers must match the types exactly. Note the %% in the rate prompt — that's an escaped percent sign, printed as a literal %. Without the double-percent, printf would try to interpret %) as a format specifier and produce undefined behavior.
5. The computation
A = P * pow(1.0 + r / n, n * t); — the whole formula in one line. Let's evaluate it step by step for the $1000 example:
r / n= 0.05 / 12 = 0.00416667 (the per-month rate)1.0 + r / n= 1.00416667 (the per-month growth factor)n * t= 12 × 10 = 120 (total months)pow(1.00416667, 120)≈ 1.647009 (the total growth factor)P * 1.647009= 1000 × 1.647009 ≈ 1647.01 (final amount)
The 1.0 + (with the decimal) is important because it forces floating-point arithmetic. If you wrote 1 + r / n, and r and n were both integers, the division would be integer division and truncate. Here r is already double, so r / n is double — but writing 1.0 + instead of 1 + is good defensive practice, in case someone later changes r to int.
6. The pow function
pow(x, y) returns x raised to the power y. Both arguments are double; the return is double. So pow(2.0, 3.0) returns 8.0. The function is declared in <math.h>.
pow is more expensive than * but far more general. For integer exponents, you could multiply in a loop — pow(x, 3) = x * x * x — but for a variable exponent like n*t, you need a loop or the pow function. The library version handles edge cases (negative exponents, fractional exponents, overflow) that a naive loop would miss. Use pow unless you have a specific reason not to.
7. Printing the result
Two printf calls print the final amount and the total interest. The first prints A; the second prints A − P. Both use %.2lf for two decimal places, and both use a $ prefix to indicate currency.
The \n at the start of the first output puts a blank line between the input section and the result — a visual separator that makes the output easier to read.
8. The nested-style comment structure
The comments in this program are structured hierarchically. The header block at the top explains the whole formula. Each section (declarations, input, computation, output) has its own block explaining its purpose. The computation block decomposes the formula into named sub-expressions. The variable declaration block lists what each variable means.
This is not literal nesting — the comments don't contain other comments. But visually, they're nested: the top-level comment contains a summary, the section comments elaborate, and the sub-expression comments drill into details. A reader can zoom in from "what is this program?" to "what is this line?" in stages.
This is the technique the assignment asks for. True C nesting isn't possible, but hierarchical documentation achieves the same goal. A well-structured comment block — one that decomposes a complex formula into understandable pieces — is exactly what complex code needs.
9. The alternative: decompose into intermediate variables
The second variant decomposes the formula into named intermediate variables: perPeriodRate, growthPerPeriod, totalPeriods, totalGrowth. This is a common alternative to nested comments — instead of explaining the sub-expressions in comments, name them.
The advantage of named variables is that they're type-checked and debuggable. If a calculation goes wrong, you can print each intermediate and see where the error occurred. Comments can't be inspected by a debugger, and they can go stale if the code changes. Named variables are self-documenting and stay in sync with the code.
The trade-off is verbosity — four extra variables means four extra lines. For a formula with four layers of nesting, that's usually worth it. For a trivial two-step formula, the single expression is fine. Choose based on complexity: the more nested the formula, the more the named-variables approach pays off.
10. Common mistakes with this formula
A few traps to watch for:
- Integer division: if
randnare integers,r / ntruncates. Usedoubleforr, or write(double)r / n. - Forgetting
-lm: on Linux, forgetting to link with the math library gives "undefined reference to pow" at link time. Add-lmafter the source file in thegcccommand. - Percent formatting: using
%alone inprintf(not%%) is undefined behavior. Escape it. - Wrong exponent:
n * t(periods × years), notn + t(periods + years) orn / t. Read the formula carefully. - Overflow: for large principals or long time periods, the result can exceed the range of
double(roughly 10^308). For realistic financial scenarios, that's fine, but for larger inputs, you'd need bignum arithmetic.
🎯 Key idea: a complex formula can be documented in two complementary ways — structured comments (hierarchical explanation) and named intermediate variables (self-documenting code). Both make the formula understandable; using both together gives the clearest result. But don't over-document — a comment that just restates the code adds noise. Explain the why, not the what.
Frequently Asked Questions
1. Can I really nest block comments in C?
No. The C standard explicitly says block comments do not nest. /* outer /* inner */ outer */ terminates at the first */, leaving the rest as active code. What's called "nested comments" in informal usage is actually "hierarchical comments" — comments that visually describe nested structure without literally nesting. This assignment uses hierarchical comments to document a complex formula.
2. Why use pow instead of writing a loop?
pow is more efficient (it uses exp and log internally, plus optimizations), handles fractional exponents, and handles negative exponents. A naive loop like for (i = 0; i < n; i++) result *= base; works only for non-negative integer exponents and is slower. For the compound-interest formula, pow is the right tool. It's also more readable — pow(x, y) matches the mathematical notation exactly.
3. Why do I need -lm when linking on Linux?
Because the math functions in <math.h> are compiled into a separate library, libm, not into the standard C library. On most Unix-like systems, the linker doesn't link libm by default. Adding -lm to the compile command tells it to include the math library. On macOS and on Windows with MSVC, math functions are in the default library, so -lm isn't needed. This is a Linux/Unix-specific quirk that trips up many beginners.
4. What's the difference between compounding monthly and annually?
Monthly compounding means interest is added 12 times per year; annually means once per year. Monthly compounding yields more total interest because each month's interest also earns interest in subsequent months. For 5% annual rate over 10 years on $1000: annual compounding gives $1628.89, monthly gives $1647.01 — about $18 more, purely from frequency. The limit as frequency approaches infinity is continuous compounding, which gives $1648.72 — only $1.71 more than daily. So most of the benefit comes from going from annual to monthly, not monthly to daily.
5. Why does the program use %d for some inputs and %lf for others?
Because the input types differ. %d reads an int — used for n (compounding periods per year) and t (years), which are whole numbers. %lf reads a double — used for P (principal, which may have cents) and r (rate, which is fractional like 0.05). Using the wrong specifier for a given type produces undefined behavior — the bytes are reinterpreted incorrectly, giving garbage values.
6. Can I use float instead of double?
Technically yes, but double is the safer default. float has about 7 significant decimal digits; double has 15. For compound-interest calculations, that precision can matter — especially for long time periods, where small rounding errors compound. Also, pow returns double, so using float variables would introduce implicit conversions. On modern hardware, double is as fast or nearly as fast as float, so there's no performance reason to prefer float.
💡 Tip: once this works, try the same program with continuous compounding: A = P * exp(r * t); — using exp instead of pow. Compare the results for the same inputs. You'll see that continuous compounding gives a slightly higher result than any finite compounding frequency (since it's the limit as n → ∞). The math behind this — the constant e and its relationship to pow — is one of the most beautiful ideas in calculus.