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
The above line creates a constant named PI with the value 3.14159.Another way to create constants is by using the
This creates a constant named TAX_RATE with the value 0.07. Note that attempting to modify a constant variable after it has been defined will result in a compilation error.Use constants in your program like regular variables:
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.
#define directive:#define PI 3.14159const keyword:const float TAX_RATE = 0.07;float area = PI * radius * radius;
float tax = price * TAX_RATE;Challenge
EasyCreate a program that calculates the area of a circle. Your program should:
- Define a constant PI with the value
3.14159 - Calculate the area of the circle using the formula:
area = PI * radius * radius - Print the calculated area with exactly 2 decimal places in the format:
Area: X.XXfollowed by a newline
radius = 5 and either float or double for the area variable.Expected output:
Area: 78.54Note: Use
%.2f as the format specifier in printf, and end your output with \n.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;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge