Declare and use variables and constants

Resources | Subject Notes | Computer Science

Variables and Constants in Programming

Introduction

In programming, variables and constants are fundamental concepts used to store and manage data. Understanding how to declare and use them is crucial for writing effective and flexible programs.

Variables

A variable is a named storage location in the computer's memory that can hold a value. The value stored in a variable can be changed during the execution of a program.

Declaration: To use a variable, it must first be declared. Declaration involves specifying the variable's name and its data type.

Data Types: Common data types include:

  • Integer (int): Whole numbers (e.g., 10, -5, 0).
  • Real (float): Numbers with decimal points (e.g., 3.14, -2.5).
  • Character (char): A single character (e.g., 'A', 'z', '5').
  • String (str): A sequence of characters (e.g., "Hello", "123").
  • Boolean (bool): Represents truth values, either True or False.

Example (Python):

x = 10  # Declares an integer variable 'x' and assigns it the value 10
name = "Alice" # Declares a string variable 'name' and assigns it the value "Alice"
is_valid = True # Declares a boolean variable 'is_valid' and assigns it the value True

Using Variables: Once declared, variables can be used in calculations, output, and other operations.

Example (Python):

y = x + 5  # Assigns the result of x + 5 to the variable 'y'
print(name) # Outputs the value of the variable 'name'

Constants

A constant is a named storage location whose value cannot be changed after it has been assigned. Constants are used to represent values that remain fixed throughout the program's execution.

Declaration: The way constants are declared varies depending on the programming language. Some languages have specific keywords for declaring constants, while others use naming conventions to indicate that a variable should be treated as a constant.

Example (Python - Convention): In Python, constants are typically named using uppercase letters.

PI = 3.14159 # 'PI' is treated as a constant
GRAVITY = 9.81 # 'GRAVITY' is treated as a constant

Using Constants: Constants are used when a value is known in advance and should not be altered. This improves code readability and helps prevent accidental modifications.

Example (Python):

radius = 5
area = PI * radius * radius
print(area)

Table: Variables vs. Constants

Feature Variable Constant
Value can be changed? Yes No
Purpose Store data that may change during program execution Store fixed values that do not change
Naming Convention (Example) Lowercase (e.g., count) Uppercase (e.g., MAX_VALUE)

Summary

Variables and constants are essential tools for managing data in programs. Variables provide flexibility by allowing values to change, while constants ensure that certain values remain fixed. Understanding the difference between them and how to use them correctly is a fundamental skill in programming.