In C++, variables are used to store and manipulate data. They are like containers that can hold different types of values, such as numbers or strings.
To declare a variable in C++, you need to specify its data type and name. For example, to declare an integer variable x
and assign it the value 5
, you would write:
1int x = 5;
You can then use this variable in calculations or to perform other operations. For instance, you can declare another integer variable y
with the value 3
, and calculate the sum of x
and y
using the addition operator +
:
1int sum = x + y;
Constants, on the other hand, are like variables but with values that cannot be changed once they are assigned. They are useful when you have a value that remains constant throughout your program. To declare a constant in C++, you use the const
keyword. For example, to declare a constant named PI
with the value 3.14159
, you would write:
1const int PI = 3.14159;
You can then use this constant in calculations or other operations, just like a variable. For instance, you can declare a double variable radius
and assign it the value 2.5
, and calculate the area of a circle using the formula PI * radius * radius
.
Here's an example that demonstrates declaring and using variables and constants in C++ for mathematical calculations:
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Declaring and using variables in C++
6 int x = 5;
7 int y = 3;
8 int sum = x + y;
9
10 // Declaring and using constants in C++
11 const int PI = 3.14159;
12 double radius = 2.5;
13 double area = PI * radius * radius;
14
15 // Outputting the results
16 cout << "Sum: " << sum << endl;
17 cout << "Area: " << area << endl;
18
19 return 0;
20}
xxxxxxxxxx
using namespace std;
int main() {
// Declaring and using variables in C++
int x = 5;
int y = 3;
int sum = x + y;
// Declaring and using constants in C++
const int PI = 3.14159;
double radius = 2.5;
double area = PI * radius * radius;
// Outputting the results
cout << "Sum: " << sum << endl;
cout << "Area: " << area << endl;
return 0;
}