Menu
Coddy logo textTech

Constants

Part of the Fundamentals section of Coddy's C journey — lesson 10 of 63.

Constants in C are variables whose values cannot be changed during program execution. They are useful for values that should remain fixed throughout your program.

Define a constant using the #define directive:

#define PI 3.14159

The above line creates a constant named PI with the value 3.14159.

Another way to create constants is by using the const keyword:

const float TAX_RATE = 0.07;

This creates a constant named TAX_RATE with the value 0.07.

Use constants in your program like regular variables:

float area = PI * radius * radius;
float tax = price * TAX_RATE;

Constants make your code more readable and easier to maintain. If you need to change a value used in multiple places, you only need to update it once.

challenge icon

Challenge

Easy

Create a program that calculates the area of a circle. Your program should:

  1. Define a constant PI with the value 3.14159
  2. Calculate the area of the circle using the formula: area = PI * radius * radius
  3. Print the calculated area with exactly 2 decimal places in the format: Area: X.XX followed by a newline
Use radius = 5 and either float or double for the area variable.

Expected output:
Area: 78.54

Note: Use %.2f as the format specifier in printf, and end your output with \n.

Cheat sheet

Constants in C are variables whose values cannot be changed during program execution.

Define a constant using the #define directive:

#define PI 3.14159

Another way to create constants is by using the const keyword:

const float TAX_RATE = 0.07;

Use constants in your program like regular variables:

float area = PI * radius * radius;
float tax = price * TAX_RATE;

Try it yourself

#include <stdio.h>

int main() {
    // Define your PI constant here
    
    int radius = 5;
    
    // Calculate the area here
    
    // Print the area here
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals