Introduction Assignment 1 — Area of a Circle Using Single-Line Comments
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Area of a Circle Using Single-Line Comments

📑 On this page:
  • What comments are, and why use them
  • Designing the area-of-circle program
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What single-line comments are, and the // syntax
  • Why comments matter — readability, intent, and maintainability
  • How to declare a double variable for precise decimal values
  • How to read input with scanf using the %lf format specifier
  • How to compute area with the formula πr²
  • How to format output to a fixed number of decimal places with %.2lf

What comments are, and why use them

A comment is text in a source file that is ignored by the compiler but read by humans. Comments don't affect the compiled binary — they exist purely to explain what the code does, why it does it, and any non-obvious details a future reader might need. They're the difference between code that runs and code that can be maintained.

C supports two kinds of comments. Single-line comments start with // and extend to the end of the line. Multi-line comments start with /* and end with */ — they can span any number of lines. Since C99, both forms are standard. Older C (C89) only officially supported the multi-line form, but almost every compiler has accepted // for decades. This assignment uses the single-line form throughout.

A good comment explains why, not what. If the code says area = PI * r * r;, a comment saying "multiply PI by r by r" adds nothing — the code already says that. A comment saying "area = πr², with r in same units as input" is useful. Comments should explain intent, assumptions, edge cases, and any non-obvious reasoning. They should not restate what the code already makes clear.

💡 In one line: // starts a single-line comment that runs to the end of the line. The compiler ignores everything after it. Use it to explain your code to the next person who reads it — often yourself, six months later.

Diagram of a circle with radius r, showing the area formula πr², and a C code snippet with single-line comments.

The program computes the area of a circle from its radius. The mathematical formula is A = πr², where π (pi) is approximately 3.14159265358979 and r is the radius. For a circle of radius 5, the area is about 78.54. The program will ask the user for the radius, compute the area, and print it — with a single-line comment on every statement explaining what's happening.

Designing the area-of-circle program

The design has five decisions that matter:

Decision Choice Reason
Variable type for radiusdoubleRadius can be fractional (e.g., 5.5 cm). int would truncate.
Value of π3.141592653589793Sufficient precision for most practical purposes. Using M_PI from <math.h> is also fine.
Input methodscanf("%lf", &radius)%lf is the format specifier for reading a double.
Output format%.2lfTwo decimal places — enough precision without visual clutter.
Comments// on every statementThe assignment specifically asks for single-line comments to document the code.

Why double and not float? float has about 7 significant decimal digits of precision; double has about 15. For a simple area calculation, float would work, but double is the default type for floating-point literals in C and avoids subtle rounding surprises. Also, on modern hardware, double arithmetic is as fast as float (or nearly so), so there's rarely a reason to use float unless you're optimizing for memory in a large array.

The constant π can be defined as a const double or a #define macro. A const variable is type-checked and respects scope; a macro is a plain text substitution. Modern style favors const double PI = 3.141592653589793;. If you include <math.h>, you can use the standard M_PI constant instead (though M_PI is technically non-standard, it's supported by virtually every compiler). For this assignment, defining your own constant is clearer and doesn't require the extra header.

🎯 Key idea: use double for any value that can be fractional. The formula is simple, but getting the types right is what separates a correct program from one that silently gives wrong answers (like using int and truncating every area to an integer).

Complete C Program

Program: area of circle with single-line comments on every line

#include <stdio.h>                    // Include standard I/O library for printf and scanf

int main(void) {                        // Program entry point
    double radius;                      // Declare the radius variable (double for fractional values)
    double area;                        // Declare the area variable (also double)
    const double PI = 3.141592653589793; // Define PI as a constant (15 significant digits)

    printf("Enter the radius of the circle: ");  // Prompt the user for input
    scanf("%lf", &radius);               // Read a double into radius; note the &

    area = PI * radius * radius;        // Compute area = πr²

    printf("Area of the circle: %.2lf\n", area);  // Print area with 2 decimal places

    return 0;                           // Return success to the operating system
}
                                    

Every line has a comment. That's not always good style — in production code, commenting every trivial line is noise — but for a beginner's first program, it's exactly the right level of detail. Every statement is accounted for, and every non-obvious syntax (the %lf, the &, the %.2lf) is explained.

Notice the const on PI. It tells the compiler: "this variable will not change." If you accidentally try to write PI = 3.14; later, the compiler will reject it. That's a useful safety net, and it also documents intent — anyone reading the code knows PI is meant to be a constant.

And here is the same program without the comments, so you can see how much cleaner (and harder to understand) code looks without explanation:

Same program, no comments

#include <stdio.h>

int main(void) {
    double radius;
    double area;
    const double PI = 3.141592653589793;

    printf("Enter the radius of the circle: ");
    scanf("%lf", &radius);

    area = PI * radius * radius;

    printf("Area of the circle: %.2lf\n", area);

    return 0;
}
                                    

This version runs identically, but a reader has to reconstruct the intent from the variable names and the formula. For an expert, that's easy. For a beginner (or an expert six months later who's forgotten the context), the commented version is far more useful. The general guideline: comment the why, not the what. For an assignment asking explicitly for comments, comment thoroughly.

Program Output

Here is typical output for a radius of 5:

Enter the radius of the circle: 5
Area of the circle: 78.54
                                

Check: π × 5² = 3.14159 × 25 = 78.53975. Rounded to two decimals, that's 78.54. Correct.

For a radius of 2.5:

Enter the radius of the circle: 2.5
Area of the circle: 19.63
                                

Check: π × 2.5² = 3.14159 × 6.25 = 19.6349. Rounded, 19.63. Correct. And notice the input was fractional — this is where the choice of double matters. If radius were an int, scanf("%d", &radius) with input 2.5 would read 2 and ignore the .5 — the user would silently get the wrong answer with no error.

For a radius of 0:

Enter the radius of the circle: 0
Area of the circle: 0.00
                                

A circle of radius 0 is a degenerate circle (a point), so area 0 is correct. This is a useful edge case to test — programs that work on normal inputs sometimes break on zero, and it's worth knowing what to expect.

For a very large radius:

Enter the radius of the circle: 1000000
Area of the circle: 3141592653589.79
                                

Radius 1,000,000 → area 3.14 × 10¹². That's over 3 trillion square units. The double type handles this fine (its range is enormous — up to about 1.8 × 10³⁰⁸), though precision is limited to about 15 significant digits, so the last several digits shown are approximate. For most practical purposes, this doesn't matter.

🔍 Try this: remove the comment on any line and rerun the program. It behaves identically — that's the whole point of comments: they never affect the program's behavior, only its readability. Then try changing double to int for radius and area, and see what happens with a radius of 2.5. You'll get the integer area (truncated), not the exact one. That demonstrates the type-sensitivity of C.

Step-by-Step Explanation

Let's walk through the program line by line. The code comments do the same thing, but this is the place to go deeper into why each piece is needed.

1. The header include

#include <stdio.h> — this is a preprocessor directive (not a C statement — note the missing semicolon). It tells the preprocessor to paste the contents of stdio.h (the standard I/O header) into the source file before compilation. That header declares printf and scanf — without it, the compiler would complain that those functions are undeclared.

The #include line doesn't execute at runtime — it's entirely handled by the preprocessor. It affects only compilation. This is a subtle but important distinction: #include and other # directives are not C statements; they're instructions to the preprocessor that runs before the compiler.

2. The main function

int main(void) — this declares the entry point of the program. int means it returns an integer (conventionally 0 for success), and (void) means it takes no arguments (for the simplest programs). The operating system calls main when the program starts; when main returns, the program ends and the return value is passed back to the OS.

The opening brace { marks the start of main's body. Every statement inside the braces is executed in order, top to bottom.

3. Declaring the variables

double radius; and double area; — these declare two variables of type double, a 64-bit floating-point type that can hold fractional values with about 15 significant decimal digits. radius will hold the circle's radius, area will hold the computed area.

Why double instead of int? Because radii are often fractional (e.g., 3.5 cm), and areas are almost always fractional (unless the radius happens to be zero or a very specific value). An int variable would truncate 3.5 to 3, and the area calculation would be silently wrong. Using double throughout avoids that whole class of bugs.

4. Defining PI

const double PI = 3.141592653589793; — declares a constant of type double, initialized to a value of π good to about 15 digits. The const qualifier means the compiler will refuse any attempt to modify PI later — if you accidentally write PI = 3.14; on some line, you get a compile error, not a silent wrong answer.

Why not just write the literal 3.141592653589793 in the area formula? Because it appears once here and could appear in many places if the program grew. Changing it in one place is easier than changing it everywhere. The const also names it — PI is more readable than 3.141592653589793.

5. The input prompt

printf("Enter the radius of the circle: "); — prints a prompt to the user. Note there's no \n at the end. The prompt and the number the user types will appear on the same line, which is standard for interactive prompts. The program waits for input because scanf on the next line will block until it receives data.

6. Reading the radius

scanf("%lf", &radius); — reads a double from standard input into the variable radius. Two things to notice:

  • %lf is the format specifier for reading a double. (The lf stands for "long float" — historically, that was the C name for double.) For float you'd use %f; for int, %d. Using the wrong specifier causes undefined behavior — the data would be misinterpreted.
  • &radius is the address of the variable, not its value. scanf needs an address because it writes into the variable. If you wrote scanf("%lf", radius) (without the &), the program would interpret the uninitialized value of radius as an address and write to it — almost certainly a crash.

7. Computing the area

area = PI * radius * radius; — the computation. The right side evaluates to PI times radius times radius, i.e., πr². The left side is the storage location where the result is written. All operands are double, so the arithmetic is done in double precision — no truncation.

Note the two multiplications: PI * radius * radius. Multiplication is left-associative, so this parses as (PI * radius) * radius. Multiplication is commutative, so the order doesn't matter — radius * radius * PI would give the same answer. Use whichever reads more naturally.

8. Printing the result

printf("Area of the circle: %.2lf\n", area); — prints the label, then the value of area formatted to exactly two decimal places. The %.2lf specifier: % starts the spec, lf says double, and .2 means "two digits after the decimal point." So 78.53975 becomes 78.54. The \n at the end is a newline — without it, the next prompt or shell prompt would run onto the same line.

Using %lf (no precision specifier) would print the full double precision — something like 78.53981633974483. That's accurate but visually noisy. %.2lf is a compromise: two decimals are plenty for a radius input to two decimals.

9. Returning from main

return 0; — signals successful completion. When the program returns 0 from main, the shell sees exit status 0, which conventionally means "no error." Nonzero values indicate failure. For simple programs, the return value is rarely inspected, but it's good practice and required by the C standard for int main. (Some older code omits it — the C99 standard says returning from main without return is equivalent to returning 0, so it's not a bug, just bad style.)

10. What the comments are doing

Each comment either states the intent of the line (// Prompt the user for input), points out a subtle detail (// note the &), or names the mathematical formula (// Compute area = πr²). None of them restate the code verbatim. That's the right level of commenting for a learning program.

In production code, some of these comments would be overkill. You don't need to comment return 0; — it's self-explanatory. But for a first program, every line is worth explaining, because every line contains something you might not understand yet. The skill is knowing when to stop commenting — when the code speaks for itself, and when a comment adds value. That judgment comes with practice.

11. A common bug: scanf without &

If you write scanf("%lf", radius) instead of scanf("%lf", &radius), the program compiles (with warnings if -Wall is on) but crashes at runtime. Here's why: scanf expects a pointer, so it interprets the argument as an address. Since radius is double, it holds some uninitialized bit pattern, which is treated as a memory address. scanf tries to write to that address, which is almost certainly invalid, causing a segfault.

This is a beginner's classic. Always pass the address with & to scanf for scalar types. (For strings — character arrays — you don't need & because the array name already decays to a pointer.)

🎯 Key idea: the choice of double for radius and area is not optional — it's what makes the program correct for fractional radii. Try changing double to int and test with 2.5. You'll get the integer-truncated result, which is wrong. The compiler won't warn you. This is why understanding types matters.

Frequently Asked Questions

1. What is the difference between // and /* */ comments?

// starts a single-line comment that runs to the end of the line. /* starts a block comment that continues until */ — it can span multiple lines, or sit in the middle of a line. Both are ignored by the compiler. Since C99, both forms are standard. Most modern style guides prefer // for single-line remarks and /* */ for multi-line blocks, function documentation, or temporarily disabling code.

2. Why use double instead of float for the radius?

float has about 7 significant decimal digits of precision; double has about 15. For a simple area calculation, float would be fine, but double is the default for floating-point literals in C — writing 3.141592653589793 gives a double, not a float. Using double throughout also avoids subtle bugs from implicit conversions. On modern hardware, double is often as fast as float, so there's no reason to use float unless you're optimizing memory in a large array.

3. Why does scanf need &radius and not just radius?

scanf needs the address of the variable so it can write into it. &radius is the address; radius is the current value (which is uninitialized garbage). If you pass radius instead of &radius, scanf interprets the garbage value as an address and tries to write there — almost certainly a crash. This is one of the most common beginner mistakes in C.

4. Why is PI declared as const instead of #define PI 3.14159?

Both work, but const has advantages: it's type-checked (the compiler knows it's a double), it respects scope (a const inside a function is local to that function), and it's debuggable (you can inspect it in a debugger, unlike a macro which is replaced by the preprocessor). #define is a text substitution — the preprocessor replaces every PI with 3.14159 before compilation. Older code uses #define because const was less well-supported in early C compilers, but modern style prefers const.

5. What happens if the user enters a negative radius?

Mathematically, a negative radius doesn't make sense, but the program would compute a positive area anyway (since r² is positive regardless of the sign of r). A truly robust program would check if (radius < 0) and print an error. For a first program, this check is often omitted — the point is to demonstrate the formula, not handle every possible bad input. But as an exercise, add the check and see how it works.

6. Why two decimal places for the output?

Because two decimals is a reasonable default for typical problems — enough precision to be useful, not so much that the output is noisy. For radius input to two decimals, the area is accurate to about two decimals after rounding. You could use %.4lf for more precision, or %.0lf for an integer-looking output. The choice depends on the application; %.2lf is a common default for general-purpose output.

💡 Tip: once this works, try the same formula with a circumference formula instead (C = 2πr). Then try a sphere's volume (V = 4/3 πr³) — notice how you'll need to handle the fraction 4/3 correctly (integer division would give 1, not 1.333). That's the same type-sensitivity trap, and it's worth seeing it in action.

📖 Related Tutorials

  • Next: Addition of Two Numbers with Multi-Line Comments
  • Nested Comments for a Complex Formula
  • Structure of a C Program
  • Basic Input/Output Statements
  • Built-in Data Types in C
  • Constants and Literals
  • All 13 Introduction to C Assignments

Previous Topic: -->> Introduction to C Assignments Index   ||   Next Topic: -->> 2. Addition of Two Numbers with Multi-Line Comments


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.