C++ Variables, constants, and expressions
Variables and constants are used to store values in C++ programs, and expressions are used to combine and manipulate these values. Here's a brief overview of each:
Variables:
- Variables are used to store values that can change during the execution of a program.
- To declare a variable, you specify its data type and name, like this:
int age;
ordouble price;
. - You can then assign a value to the variable using the assignment operator (=), like this:
age = 25;
orprice = 3.14;
. - You can also declare and assign a value to a variable in a single statement, like this:
int count = 0;
.
Constants:
- Constants are used to store values that cannot be changed during the execution of a program.
- To declare a constant, you use the
const
keyword, like this:const int MAX_VALUE = 100;
orconst double PI = 3.14;
. - Once a constant is declared and initialized, its value cannot be changed.
Expressions:
- Expressions are combinations of values, variables, and operators that are used to perform calculations or comparisons.
- For example,
3 + 4
is an expression that evaluates to the value 7. - Expressions can also include variables and constants, like this:
age + 1
orPI * radius * radius
. - C++ supports a wide range of operators for combining values and variables into expressions, including arithmetic operators like +, -, *, and /, as well as comparison operators like ==, !=, <, >, <=, and >=.
Here's an example that combines variables, constants, and expressions in a C++ program:
cpp#include <iostream>
using namespace std;
int main()
{
const double PI = 3.14;
int radius = 5;
double area;
area = PI * radius * radius;
cout << "The area of a circle with radius " << radius << " is " << area << endl;
return 0;
}
This program declares a constant PI
and a variable radius
, and then uses these values to calculate the area of a circle using the expression PI * radius * radius
. The cout
statement is used to print the result to the console.
Comments
Post a Comment