Function Assignment 6 — Convert Temperature from Celsius to Fahrenheit Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Convert Temperature from Celsius to Fahrenheit Using a Function

📑 On this page:
  • The formula — and the trap hiding in it
  • Designing the celsiusToFahrenheit function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to write a function with a real-world formula
  • Why writing 9/5 instead of 9.0/5.0 breaks the calculation
  • What integer division is, and how to avoid it
  • How to test a conversion function against known reference points (freezing, boiling)
  • How to make the same function work in both directions

The formula — and the trap hiding in it

The Celsius to Fahrenheit formula is F = (C × 9/5) + 32. Water freezes at 0°C = 32°F; it boils at 100°C = 212°F; room temperature is about 22°C = 71.6°F. If you plug in 100, you get (100 × 9/5) + 32 = (100 × 1.8) + 32 = 180 + 32 = 212. Everything checks out.

Now here's the trap. In C, 9/5 is not 1.8. It's 1. Because 9 and 5 are both integers, C performs integer division, which throws away the fractional part. So 9/5 becomes 1, and the formula becomes F = C × 1 + 32, which is wrong — and not obviously wrong. For 100°C, you'd get 132°F instead of 212°F. For 0°C, you'd get 32°F, which happens to be right, so the bug slips past a quick test. Beginners chase this bug for hours.

The fix is to make the division happen in floating-point arithmetic. Write 9.0/5.0, or 9.0/5, or 9/5.0 — any of these forces a floating-point division and produces 1.8. Or, even simpler, write 1.8 directly if you don't need the derivation to be visible. The formula itself doesn't care; only the arithmetic does.

This assignment is the first one that puts a real, well-known formula into a function — which makes the integer-division trap especially valuable to encounter. It's the kind of mistake you make once, remember forever, and then spot in other people's code. Writing the function here gives you the chance to make that mistake in a controlled setting.

⚠️ The trap: 9/5 is 1 in C, not 1.8. Use 9.0/5.0 (or just 1.8) so the arithmetic stays in floating point. Everything else about the function is straightforward.

A thermometer showing both Celsius and Fahrenheit scales, highlighting key reference points like 0°C = 32°F and 100°C = 212°F.

Designing the celsiusToFahrenheit function

The signature is the same pattern as rectangleArea from assignment 5:

Part Choice Why
Function namecelsiusToFahrenheitDescribes the direction of conversion explicitly. If you also have a Fahrenheit-to-Celsius function, having both names is clearer than convert and convertBack.
Parameterfloat cTemperatures are fractional. Using int would truncate 22.5°C to 22, which changes the result.
Return typefloatThe formula involves multiplication by 1.8 — a non-integer — so the result is fractional.

That gives us:

float celsiusToFahrenheit(float c);
                                

And the definition:

float celsiusToFahrenheit(float c) {
    return (c * 9.0 / 5.0) + 32.0;
}
                                

The 9.0 and 5.0 are float literals. Since one operand of the division is float, the division is done in floating-point arithmetic, and the result is 1.8. The 32.0 is technically unnecessary (C would promote the int 32 to float), but writing it that way makes the intent clear — every literal in the expression is a float, so there's no ambiguity about which arithmetic is happening. It's a stylistic choice, and one that makes bugs easier to spot.

One extra consideration for this function: unlike the previous ones, there's a real opportunity for a second function that converts the other direction:

float fahrenheitToCelsius(float f) {
    return (f - 32.0) * 5.0 / 9.0;
}
                                

These two functions are inverses of each other: fahrenheitToCelsius(celsiusToFahrenheit(x)) == x, up to floating-point rounding. That inverse relationship is a great way to test both functions — if the round-trip gives you back what you started with, you know they're both correct (assuming the initial direction is tested against known values). Keep this idea in mind when you write the tests for this program.

Complete C Program

Program: read Celsius, convert, print Fahrenheit

#include <stdio.h>

/* Function prototype */
float celsiusToFahrenheit(float c);

int main(void) {
    float celsius, fahrenheit;

    printf("Enter temperature in Celsius: ");
    scanf("%f", &celsius);

    fahrenheit = celsiusToFahrenheit(celsius);

    printf("%.2f°C = %.2f°F\n", celsius, fahrenheit);

    return 0;
}

/* Function definition */
float celsiusToFahrenheit(float c) {
    return (c * 9.0 / 5.0) + 32.0;
}
                                    

And here's a version with both directions — the useful one if you're going to use this as a real converter:

Variant: bidirectional converter

#include <stdio.h>

float cToF(float c) { return (c * 9.0 / 5.0) + 32.0; }
float fToC(float f) { return (f - 32.0) * 5.0 / 9.0; }

int main(void) {
    int choice;
    float temp;

    printf("1. Celsius to Fahrenheit\n");
    printf("2. Fahrenheit to Celsius\n");
    printf("Enter choice: ");
    scanf("%d", &choice);

    if (choice == 1) {
        printf("Enter Celsius: ");
        scanf("%f", &temp);
        printf("%.2f°C = %.2f°F\n", temp, cToF(temp));
    } else if (choice == 2) {
        printf("Enter Fahrenheit: ");
        scanf("%f", &temp);
        printf("%.2f°F = %.2f°C\n", temp, fToC(temp));
    } else {
        printf("Invalid choice.\n");
    }

    return 0;
}
                                    

And here's a test program that checks the conversion against known reference points and verifies the round-trip:

Variant: verify against reference points

#include <stdio.h>

float cToF(float c) { return (c * 9.0 / 5.0) + 32.0; }

int main(void) {
    float test_celsius[] = {0.0, 100.0, -40.0, 37.0, 22.0};
    float expected_f[]   = {32.0, 212.0, -40.0, 98.6, 71.6};

    printf("Celsius -> Fahrenheit (comparing to expected)\n");
    for (int i = 0; i < 5; i++) {
        float got = cToF(test_celsius[i]);
        printf("%7.1f°C -> %7.1f°F  (expected %7.1f)  %s\n",
               test_celsius[i], got, expected_f[i],
               (got - expected_f[i] < 0.01 && expected_f[i] - got < 0.01) ? "OK" : "FAIL");
    }

    return 0;
}
                                    

This test harness compares the function's output to expected values. It's a small step toward a proper unit test — the kind you'd write for production code. Notice the -40°C = -40°F case: it's the one point where the two scales meet, and it's a useful test because it exercises the formula with a negative input. Also notice the 0.01 tolerance in the comparison — floating-point values often can't be compared with == exactly, so you compare within a small epsilon.

Program Output

A typical run of the first program:

Enter temperature in Celsius: 100
100.00°C = 212.00°F
                                

At freezing:

Enter temperature in Celsius: 0
0.00°C = 32.00°F
                                

At body temperature:

Enter temperature in Celsius: 37
37.00°C = 98.60°F
                                

At the point where the scales meet:

Enter temperature in Celsius: -40
-40.00°C = -40.00°F
                                

For the test harness:

Celsius -> Fahrenheit (comparing to expected)
    0.0°C ->    32.0°F  (expected    32.0)  OK
  100.0°C ->   212.0°F  (expected   212.0)  OK
  -40.0°C ->   -40.0°F  (expected   -40.0)  OK
   37.0°C ->    98.6°F  (expected    98.6)  OK
   22.0°C ->    71.6°F  (expected    71.6)  OK
                                

Every reference point passes. Notice the 37.0°C → 98.6°F case — this is where the fractional part of 1.8 matters. If you'd written 9/5 instead of 9.0/5.0, 37 would produce 37 + 32 = 69 instead of 98.6. That's a difference of 30 degrees — not something you could miss on close inspection, but small enough that a casual reading might miss it. The test harness makes it obvious.

Step-by-Step Explanation

Let's look at the function and then walk through what makes it work — and what would break it.

1. The formula in code

(c * 9.0 / 5.0) + 32.0 is the formula written with floating-point literals. Multiplication and division have the same precedence and evaluate left-to-right, so this is ((c * 9.0) / 5.0) + 32.0. If you wanted to emphasize the 9/5 = 1.8 factor, you could write c * 1.8 + 32.0 — same result, but less transparent about where the 1.8 came from. Both are fine; the version with 9.0/5.0 shows the derivation, which is nice for anyone reading.

2. Why 9.0 and not 9?

Because 9/5 is integer division in C and produces 1. 9.0/5.0 is floating-point division and produces 1.8. The same is true for 9.0/5 or 9/5.0 — as long as one operand is floating-point, the whole division is done in floating point. The .0 on one operand is enough to lift the whole expression into float territory. Making both operands float is a defensive habit — nothing changes, but the intent is unmistakable.

3. Tracing celsiusToFahrenheit(37.0)

  1. 37.0 * 9.0 = 333.0
  2. 333.0 / 5.0 = 66.6
  3. 66.6 + 32.0 = 98.6
  4. Return 98.6. ✓ (The body temperature in Fahrenheit.)

Compare with the integer-division trap: if the expression were 37.0 * 9 / 5 + 32 with the 9/5 happening as integers, the result would be 37.0 * 1 + 32 = 69.0 — wrong by about 30 degrees. The correct arithmetic depends on writing the literals in a form that avoids integer division.

4. The return type and precision

The return type float preserves the fractional part of the answer. Since temperatures often include decimals (98.6°F, 37.5°C, etc.), this is important. If you returned int, 98.6 would become 98. If you were doing medical calculations where 0.1°F matters, that would be a real problem. Even for everyday use, losing the decimal is annoying and wrong — 37°C should be reported as 98.6°F, not 98°F.

5. The precision of float vs double

For temperatures, float is plenty — its about 7 significant digits of precision means it can represent 98.6 exactly enough for any real use. If you were doing simulations with micro-degree precision, you'd use double. For a general-purpose converter, float is fine. If you switch to double for consistency with other code, change %f in scanf to %lf (or use %f everywhere and rely on printf's automatic promotion). The body stays the same.

6. Testing against known reference points

The two most important temperature reference points are water's freezing and boiling points: 0°C = 32°F and 100°C = 212°F. Both should appear in any test suite for this function. The -40 point is famous because it's where the two scales cross: -40°C = -40°F. If a function passes all three, you can be confident it's mathematically correct. The test harness above uses all three plus two realistic values (body temperature and room temperature) for good coverage.

7. The inverse function

fahrenheitToCelsius(f) { return (f - 32.0) * 5.0 / 9.0; } — you solve the original formula for C: F = 1.8 × C + 32, so C = (F - 32) / 1.8. Writing 5.0/9.0 keeps the floating-point division intact. This is the version you'd use if you needed the reverse conversion. Having both directions makes testing easier — see the round-trip idea below.

8. The round-trip test

If fahrenheitToCelsius(celsiusToFahrenheit(x)) returns x (within a tiny epsilon), both functions are correct with high probability. This is a common testing pattern: if two operations are inverses, applying them in sequence should return you to the start. Try it with x = 25.0: 25 → 77°F → 25°C. If the output is 24.99999 or 25.00001, that's fine — floating-point arithmetic has small errors, and the round-trip won't be bit-exact. If the output is 25.0, that's a happy accident. What matters is that the error is small (within 0.0001 or so), not that it's zero.

9. Comparison with the integer-division trap

Here's the trap in slow motion. If the function were:

return (c * 9 / 5) + 32;  /* WRONG */
                                

The evaluation would be:

  1. 9 / 5 = 1 — integer division, discarded remainder
  2. c * 1 = c
  3. c + 32

For c = 100, this gives 132 — which is neither the right answer (212) nor obviously wrong to a casual reader. For c = 0, it gives 32 — which is right, so a quick test with 0 passes and the bug hides. This is why the 9.0/5.0 form is critical, and why testing against multiple reference points is essential. A single test at 0°C would miss the bug entirely.

🔍 Try this: temporarily change 9.0 / 5.0 to 9 / 5 in the function and run the test harness. Watch three of the five cases fail. Then change it back. The difference between 9.0/5.0 and 9/5 is one character — but it changes the output by tens of degrees.

Frequently Asked Questions

1. Why do we write 9.0 / 5.0 instead of 9 / 5?

Because 9 and 5 are integers, and in C, dividing two integers gives an integer result — the fractional part is discarded. 9 / 5 evaluates to 1, not 1.8. Writing 9.0 or 5.0 makes at least one operand a double, which forces the division to happen in floating-point. This is one of the most common beginner mistakes in C, and it shows up in every temperature-conversion, unit-conversion, or percentage-calculation program.

2. Can I write c * 1.8 + 32 instead?

Yes — 1.8 is exactly 9/5, so the arithmetic is identical. This form is shorter and avoids the integer-division trap entirely (since 1.8 is a double literal). Some people find it clearer — "multiply by 1.8, add 32." Others find 9.0/5.0 clearer because it shows where the 1.8 came from. Both are correct; use whichever you find more readable. Just remember that if you ever change the formula, you have to change both places.

3. Why do we get 98.60 for 37, not 98.6?

The output format is %.2f, which shows exactly two digits after the decimal point. 98.6 has one digit after the decimal, so it's displayed as 98.60 with a trailing zero. If you want to suppress trailing zeros, you'd use a different format specifier like %g, which picks a shorter representation automatically. For a display where fixed precision is desired (like a temperature reading), %.2f is standard — 98.60°F is easier to read than 98.6°F when it's part of a column of values.

4. Why use float and not double?

Either works for temperature conversion. float uses 4 bytes and has about 7 significant digits of precision — plenty for 98.6°F or 22.5°C. double uses 8 bytes and has about 15 significant digits — overkill for this application, but the default for floating-point literals in C (9.0 is a double, not a float). If you switch to double, change %f to %lf in scanf and adjust the function signature — but the arithmetic stays identical. Most modern code uses double by default and reserves float for memory-constrained situations.

5. Can the function return an int if the result is a whole number?

Technically yes, but it's a bad idea. Temperature conversion naturally produces fractional results (98.6°F, 32.5°C, etc.), and returning int would truncate them. Even for inputs that produce whole-number results (like 0°C → 32°F), the function's return type should reflect the domain — float for a continuous quantity. Returning int would surprise callers and silently lose precision on fractional inputs.

6. How can I test that the function is correct?

Use reference points. The most reliable are: 0°C = 32°F (water freezes), 100°C = 212°F (water boils), and -40°C = -40°F (the scales meet). If all three pass, the function is almost certainly correct. For extra confidence, add a round-trip test: fToC(cToF(x)) should equal x within floating-point tolerance. The test harness in the code above uses five reference points — three extreme and two realistic — and checks all of them.

💡 Tip: Once this works, try converting to Kelvin as well — K = C + 273.15. Then write a program that converts among all three scales (Celsius, Fahrenheit, Kelvin), with each pair handled by its own small function. The pattern is identical every time, and building six conversion functions gives you good practice with the same shape. You'll also learn that Kelvin has no negative values (absolute zero is 0K), which is worth thinking about when you design the validation.

📖 Related Tutorials

  • Introduction to Functions in C
  • Need for User-Defined Functions
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Built-in Data Types
  • Arithmetic Operators
  • All 33 Function Assignments

Previous Topic: -->> 5. Calculate the Area of a Rectangle Using a Function   ||   Next Topic: -->> 7. Find the GCD (Greatest Common Divisor) of Two Numbers Using a Function


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.